// Standalone Echoion host. It loads the hot-reloadable Core through CoreLoader // and adapts Echoion's host contract to VoidTeamspeak's typed client API. #include "echoion/host/CoreLoader.hpp" #include "echoion/standalone/ReleaseManifest.hpp" #include "echoion/standalone/RuntimePaths.hpp" #include "echoion/standalone/StandaloneClientInterface.hpp" #include "echoion/standalone/UpdateBuildDefaults.hpp" #include "echoion/standalone/UpdateService.hpp" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #ifndef _WIN32 #include #endif namespace { std::atomic g_updateRequested{false}; void requestUpdate() { g_updateRequested = true; } std::optional argumentValue(int argc, char** argv, std::string_view name) { for (int index = 1; index + 1 < argc; ++index) { if (std::string_view{argv[index]} == name) { return argv[index + 1]; } } return std::nullopt; } bool hasArgument(int argc, char** argv, std::string_view name) { for (int index = 1; index < argc; ++index) { if (std::string_view{argv[index]} == name) { return true; } } return false; } std::optional optionalArgumentPath(int argc, char** argv, std::string_view name) { for (int index = 1; index < argc; ++index) { if (std::string_view{argv[index]} != name) { continue; } if (index + 1 < argc && !std::string_view{argv[index + 1]}.starts_with("--")) { return std::filesystem::path{argv[index + 1]}; } return std::nullopt; } return std::nullopt; } std::optional environmentPath(const char* name) { const char* value = std::getenv(name); if (!value || std::string_view{value}.empty()) { return std::nullopt; } return std::filesystem::path{value}; } std::filesystem::path absolutePath(const std::filesystem::path& path) { std::error_code error; auto absolute = std::filesystem::absolute(path, error); return (error ? path : absolute).lexically_normal(); } struct RuntimeHandoff { std::filesystem::path manifestPath; std::string state; std::string version; std::string previousVersion; std::uint32_t retainHealthyVersions = 2; }; [[nodiscard]] std::optional retainHealthyVersions(const Void::Json::Value& object) { const auto* value = object.find("retainHealthyVersions"); if (value == nullptr) { return 2U; } if (!value->is_number()) { return std::nullopt; } const double number = value->as_number(); if (!std::isfinite(number) || std::trunc(number) != number || number < 1.0 || number > 10.0) { return std::nullopt; } return static_cast(number); } [[nodiscard]] bool pathWithin(const std::filesystem::path& path, const std::filesystem::path& root) { auto pathIterator = path.begin(); for (auto rootIterator = root.begin(); rootIterator != root.end(); ++rootIterator, ++pathIterator) { if (pathIterator == path.end() || *pathIterator != *rootIterator) { return false; } } return true; } std::optional readRuntimeHandoff(const std::filesystem::path& handoff, const std::filesystem::path& installationPrefix) { auto contents = Void::FileSystem::read_file(handoff); if (!contents) { return std::nullopt; } auto parsed = Void::Json::parse(*contents); if (!parsed || !parsed->is_object()) { return std::nullopt; } const auto stringField = [&parsed](std::string_view name) { const auto* value = parsed->find(name); return value && value->is_string() ? value->as_string() : std::string{}; }; const auto manifestValue = stringField("manifestPath"); const auto state = stringField("state"); const auto version = stringField("version"); const auto retention = retainHealthyVersions(*parsed); if (manifestValue.empty() || state.empty() || version.empty() || !retention.has_value()) { return std::nullopt; } const std::filesystem::path relativeManifest{manifestValue}; if (relativeManifest.is_absolute()) { return std::nullopt; } std::error_code error; const auto manifest = std::filesystem::canonical( installationPrefix / relativeManifest, error); if (error) { return std::nullopt; } const auto versions = std::filesystem::canonical(installationPrefix / "versions", error); if (error || !std::filesystem::is_regular_file(manifest)) { return std::nullopt; } if (!pathWithin(manifest, versions)) { return std::nullopt; } return RuntimeHandoff{.manifestPath = manifest, .state = state, .version = version, .previousVersion = stringField("previousVersion"), .retainHealthyVersions = *retention}; } [[nodiscard]] std::filesystem::path installationPrefix(const std::filesystem::path& installRoot) { std::error_code error; if (installRoot.filename() == "current" && std::filesystem::is_symlink( std::filesystem::symlink_status(installRoot, error))) { return installRoot.parent_path(); } return installRoot; } [[nodiscard]] std::filesystem::path updaterIncomingDirectory(const std::filesystem::path& root, const std::filesystem::path& stateDirectory) { if (const auto configured = environmentPath("ECHOION_INCOMING_DIR")) { return absolutePath(*configured); } if (auto record = Void::FileSystem::read_file(root / ".echoion-install")) { constexpr std::string_view prefix{"incoming_dir="}; std::string_view contents{*record}; while (!contents.empty()) { const auto end = contents.find('\n'); const auto line = contents.substr(0, end); if (line.starts_with(prefix) && line.size() > prefix.size()) { std::filesystem::path path{line.substr(prefix.size())}; return absolutePath(path.is_absolute() ? path : root / path); } if (end == std::string_view::npos) { break; } contents.remove_prefix(end + 1); } } return stateDirectory / "incoming"; } [[nodiscard]] std::optional runningReleaseManifest(const std::filesystem::path& executable, const std::filesystem::path& installRoot) { const std::array candidates{executable.parent_path().parent_path() / "manifest.json", installRoot / "manifest.json"}; for (const auto& candidate : candidates) { if (auto manifest = Echoion::Standalone::ReleaseManifest::load(candidate)) { return std::move(*manifest); } } return std::nullopt; } [[nodiscard]] std::filesystem::path reconcileManagedCore(const std::filesystem::path& stateDirectory, const std::filesystem::path& fallback) { Void::Update::VersionStore store(stateDirectory / "updates" / "components" / "core"); if (auto initialized = store.initialize(); !initialized) { Void::Log::warn("main", "Cannot initialize managed Core store: {}", initialized.error().message()); return fallback; } if (auto reconciled = store.reconcile(); !reconciled) { Void::Log::warn("main", "Cannot reconcile managed Core store: {}", reconciled.error().message()); return fallback; } auto current = store.currentVersion(); if (!current || !*current) { return fallback; } const auto managed = store.versionPath(**current) / fallback.filename(); return std::filesystem::is_regular_file(managed) ? managed : fallback; } [[nodiscard]] Echoion::Api::Result invokeRuntimeHelper(const std::filesystem::path& helper, const std::filesystem::path& root, std::string_view operationJson) { auto operation = Void::Json::parse(operationJson); if (!operation || !operation->is_object()) { return Echoion::Api::fail( Echoion::Api::ErrorCode::ParseError, "runtime update operation must be a JSON object"); } const auto field = [&operation](std::string_view name) { const auto* value = operation->find(name); return value && value->is_string() ? value->as_string() : std::string{}; }; const auto action = field("action"); const auto version = field("version"); const auto retention = retainHealthyVersions(*operation); if (!retention.has_value()) { return Echoion::Api::fail( Echoion::Api::ErrorCode::InvalidArgument, "retainHealthyVersions must be an integer from 1 to 10"); } std::string command; std::vector options; if (action == "activate") { command = "activate-runtime"; options = {"--staging", field("stagingId"), "--version", version, "--manifest-sha256", field("manifestSha256")}; } else if (action == "rollback") { command = "rollback-runtime"; options = {"--version", version}; } else if (action == "commit") { command = "commit-runtime"; options = {"--version", version}; } else { return Echoion::Api::fail(Echoion::Api::ErrorCode::InvalidArgument, "unknown runtime update operation"); } if (version.empty() || std::ranges::any_of( options, [](const auto& value) { return value.empty(); })) { return Echoion::Api::fail( Echoion::Api::ErrorCode::InvalidArgument, "runtime update operation is missing required fields"); } options.insert(options.end(), {"--retain", std::to_string(*retention)}); bool direct = false; #ifndef _WIN32 direct = ::access((root / "versions").c_str(), W_OK) == 0; #endif std::vector arguments{"--root", root.string()}; if (!direct) { arguments.insert(arguments.end(), {"request", command}); } else { arguments.push_back(command); } arguments.insert(arguments.end(), options.begin(), options.end()); if (!direct) { arguments.insert(arguments.end(), {"--origin", "daemon"}); } auto result = Void::Process::run(helper, arguments, {}, std::chrono::seconds{30}); if (!result) { return Echoion::Api::fail( Echoion::Api::ErrorCode::ServiceUnavailable, result.error().message()); } if (result->exit_code != 0) { return Echoion::Api::fail( Echoion::Api::ErrorCode::ServiceUnavailable, result->err.empty() ? "runtime update helper failed" : result->err); } return result->out.empty() ? std::string{"{}"} : std::move(result->out); } std::filesystem::path configDir() { if (const char* x = std::getenv("XDG_CONFIG_HOME")) { return std::filesystem::path(x) / "echoion"; } if (const char* h = std::getenv("HOME")) { return std::filesystem::path(h) / ".config" / "echoion"; } return std::filesystem::path(".") / "echoion"; } bool prepareStateDirectory(const std::filesystem::path& stateDirectory, bool explicitlySelected) { std::error_code error; std::filesystem::create_directories(stateDirectory, error); if (error) { std::cerr << "Cannot create state directory " << stateDirectory << ": " << error.message() << '\n'; return false; } const auto setPath = [](const char* name, const std::filesystem::path& path, bool overwrite) { const auto value = path.string(); return ::setenv(name, value.c_str(), overwrite ? 1 : 0) == 0; }; const auto temporaryDirectory = stateDirectory / "tmp"; std::filesystem::create_directories(temporaryDirectory, error); if (error) { std::cerr << "Cannot create temporary directory " << temporaryDirectory << ": " << error.message() << '\n'; return false; } if (!setPath("ECHOION_STATE_DIR", stateDirectory, true) || !setPath("XDG_CACHE_HOME", stateDirectory / "cache", explicitlySelected) || !setPath("XDG_STATE_HOME", stateDirectory / "state", explicitlySelected) || !setPath("XDG_DATA_HOME", stateDirectory / "data", explicitlySelected) || !setPath("TMPDIR", temporaryDirectory, explicitlySelected)) { std::cerr << "Cannot export runtime state paths\n"; return false; } return true; } int validateInstall(const std::filesystem::path& installRoot) { auto manifest = Echoion::Standalone::ReleaseManifest::load( installRoot / "manifest.json"); if (!manifest) { std::cerr << manifest.error().message << '\n'; return 2; } if (auto result = manifest->validateInstallLayout(); !result) { std::cerr << result.error().message << '\n'; return 2; } std::cout << "Echoion installation is valid: " << installRoot << '\n'; return 0; } void recordInterruptedRelease(const std::filesystem::path& directory) { const auto transaction = directory / "release-transaction"; if (!std::filesystem::exists(transaction) || std::getenv("ECHOION_REEXEC_VERSION")) { return; } auto version = Void::FileSystem::read_file(transaction); if (version && !version->empty()) { std::ignore = Void::FileSystem::atomic_write( directory / "failed-release", *version); Void::Log::error("main", "Release {} failed its startup health check; " "stable service restored", *version); } std::ignore = Void::FileSystem::remove_path(transaction); } std::string envOr(const char* key, const std::string& fallback) { const char* v = std::getenv(key); return v ? std::string(v) : fallback; } int envInt(const char* key, int fallback) { const char* v = std::getenv(key); if (!v) { return fallback; } try { return std::stoi(v); } catch (...) { return fallback; } } int importIdentity(int argc, char** argv, const std::filesystem::path& defaultIdentityPath) { std::optional source; auto destination = defaultIdentityPath; bool force = false; bool importRequested = false; for (int i = 1; i < argc; ++i) { const std::string_view argument{argv[i]}; if (argument == "--help") { std::cout << "Usage: echoiond [--config PATH] [--state-dir PATH]\n" " echoiond --import-identity EXPORT.ini " "[--identity-path PATH] [--force]\n" " echoiond --validate-install [ROOT]\n"; return 0; } if (argument == "--import-identity") { importRequested = true; if (i + 1 < argc && !std::string_view{argv[i + 1]}.starts_with("--")) { source = argv[++i]; } } else if (argument == "--identity-path" && i + 1 < argc) { destination = argv[++i]; } else if (argument == "--force") { force = true; } } if (!importRequested) { return -1; } if (!source) { std::cerr << "--import-identity requires an exported INI path.\n"; return 2; } try { if (std::filesystem::exists(destination) && !force) { std::cerr << "Identity already exists at " << destination << "; pass --force to replace it.\n"; return 2; } const auto identity = Void::TeamSpeak::Identity::importTeamSpeakIni(source->string()); if (const auto parent = destination.parent_path(); !parent.empty()) { std::filesystem::create_directories(parent); } identity.save(destination.string()); std::cout << "Imported TeamSpeak identity " << identity.uid() << " to " << destination << '\n'; return 0; } catch (const std::exception& error) { std::cerr << "Identity import failed: " << error.what() << '\n'; return 2; } } } // namespace int main(int argc, char** argv) { std::set_terminate([] { const auto frames = Void::Stacktrace::capture_stacktrace(); std::cerr << Void::Stacktrace::format_stacktrace(frames) << '\n'; std::abort(); }); if (hasArgument(argc, argv, "--validate-release")) { const auto validationPath = argumentValue(argc, argv, "--validate-release"); if (!validationPath || validationPath->starts_with("--")) { std::cerr << "--validate-release requires a manifest path\n"; return 2; } auto manifest = Echoion::Standalone::ReleaseManifest::load(*validationPath); if (!manifest) { std::cerr << manifest.error().message << '\n'; return 2; } if (auto result = manifest->validate(); !result) { std::cerr << result.error().message << '\n'; return 2; } return 0; } const auto runningExecutable = Echoion::Standalone::runningExecutablePath(); if (!runningExecutable) { std::cerr << runningExecutable.error() << '\n'; return 2; } const auto installRoot = Echoion::Standalone::deriveInstallRoot( *runningExecutable, environmentPath("ECHOION_HOME")); const auto updateRoot = installationPrefix(installRoot); if (hasArgument(argc, argv, "--validate-install")) { const auto requestedRoot = optionalArgumentPath(argc, argv, "--validate-install"); return validateInstall(requestedRoot ? absolutePath(*requestedRoot) : installRoot); } const auto installRootString = installRoot.string(); if (::setenv("ECHOION_HOME", installRootString.c_str(), 1) != 0) { std::cerr << "Cannot export ECHOION_HOME\n"; return 2; } if (!environmentPath("SSL_CERT_FILE")) { if (const auto certificateBundle = Echoion::Standalone::bundledCertificateBundle(installRoot)) { const auto bundleString = certificateBundle->string(); if (::setenv("SSL_CERT_FILE", bundleString.c_str(), 0) != 0) { std::cerr << "Cannot export bundled TLS certificate store\n"; return 2; } } } for (const std::string_view requiredValue : {"--config", "--state-dir"}) { if (hasArgument(argc, argv, requiredValue) && !optionalArgumentPath(argc, argv, requiredValue)) { std::cerr << requiredValue << " requires a path\n"; return 2; } } const auto cfgDir = absolutePath(configDir()); std::filesystem::path cfgPath = cfgDir / "config.json"; if (const auto requestedConfig = optionalArgumentPath(argc, argv, "--config")) { cfgPath = absolutePath(*requestedConfig); } const auto commandLineState = optionalArgumentPath(argc, argv, "--state-dir"); const auto environmentState = environmentPath("ECHOION_STATE_DIR"); const auto stateDirectory = Echoion::Standalone::resolveStateDirectory( commandLineState, environmentState, environmentPath("XDG_STATE_HOME"), environmentPath("HOME"), cfgDir); if (!prepareStateDirectory(stateDirectory, commandLineState.has_value() || environmentState.has_value())) { return 2; } auto signalWatcherResult = Void::Process::SignalWatcher::create(); if (!signalWatcherResult) { std::cerr << "Cannot install signal watcher: " << signalWatcherResult.error().message() << '\n'; return 2; } auto signalWatcher = std::move(*signalWatcherResult); recordInterruptedRelease(stateDirectory); const auto identityPath = absolutePath(std::filesystem::path(envOr( "ECHOION_IDENTITY_PATH", (stateDirectory / "identity.txt").string()))); if (const auto importResult = importIdentity(argc, argv, identityPath); importResult >= 0) { return importResult; } const auto requestedRestore = optionalArgumentPath(argc, argv, "--restore-state"); const std::optional restorePath = requestedRestore ? std::optional{absolutePath(*requestedRestore)} : std::nullopt; const auto requestedManifest = environmentPath("ECHOION_RELEASE_MANIFEST"); const auto activationHandoff = stateDirectory / "updates" / "activated-runtime.json"; const auto releaseTriggerPath = requestedManifest ? absolutePath(*requestedManifest) : activationHandoff; const bool releaseTriggerIsHandoff = !requestedManifest.has_value(); const auto runningManifest = runningReleaseManifest(*runningExecutable, installRoot); const auto runtimeVersion = runningManifest ? runningManifest->version : std::string{ Echoion::Standalone::UpdateBuildDefaults::RuntimeVersion}; if (auto recovered = Echoion::Standalone::reconcileManagedPluginUpdates(stateDirectory); !recovered) { Void::Log::error("main", "cannot recover managed plugin updates: {}", recovered.error().message); return 1; } Echoion::Standalone::StandaloneSettings settings; settings.identityPath = identityPath.string(); settings.avatarCachePath = (stateDirectory / "avatars").string(); settings.securityLevel = envInt("ECHOION_SECURITY_LEVEL", 8); settings.opusBitrate = envInt("ECHOION_OPUS_BITRATE", 96000); auto interface = std::make_shared( settings); if (auto r = interface->initialize(); !r) { Void::Log::error("main", "interface init failed: {}", r.error().message); return 1; } Echoion::Host::CoreLoader loader; loader.setConfigPath(cfgPath); const auto executableDirectory = runningExecutable->parent_path(); const auto configuredCoreOverride = environmentPath("ECHOION_CORE_PATH"); const auto configuredCorePath = Echoion::Standalone::resolveCorePath( installRoot, executableDirectory, configuredCoreOverride); const bool customCoreOverride = configuredCoreOverride && absolutePath(*configuredCoreOverride) != absolutePath(installRoot / "lib" / "Echoion.ts"); const auto corePathResolved = customCoreOverride ? configuredCorePath : reconcileManagedCore(stateDirectory, configuredCorePath); if (const auto workingDirectory = Echoion::Standalone::runtimeWorkingDirectory(installRoot, executableDirectory)) { std::error_code error; std::filesystem::current_path(*workingDirectory, error); if (error) { Void::Log::error("main", "cannot select runtime asset directory {}: {}", workingDirectory->string(), error.message()); return 1; } } Void::Log::info("main", "Loading Core from {}", corePathResolved.string()); if (auto r = loader.load(corePathResolved); !r) { Void::Log::error("main", "failed to load Core: {}", r.error().message); return 1; } if (restorePath) { if (auto result = loader.restoreCheckpoint(*restorePath); !result) { Void::Log::error("main", "failed to restore restart checkpoint: {}", result.error().message); return 1; } } auto core = loader.getCore(); if (!core) { Void::Log::error("main", "Core not available after load"); return 1; } core->setPluginInterface(interface); interface->registerEventCallback( [core](const Echoion::Api::PluginEvent& ev) { std::ignore = core->onPluginEvent(ev); }); loader.setHotReloadPrepareCallback( [interface] { interface->quiesceEventCallbacks(); }); // Re-register the Core callback after each hot reload (new Core instance). loader.setHotReloadCallback([&loader, interface] { if (auto c = loader.getCore()) { c->setPluginInterface(interface); interface->registerEventCallback( [c](const Echoion::Api::PluginEvent& ev) { std::ignore = c->onPluginEvent(ev); }); c->triggerAutoConnect(); } }); const auto updaterExecutable = runningExecutable->parent_path() / "echoion-updater"; auto updateService = std::make_unique( Echoion::Standalone::UpdateService::Options{ .configPath = cfgPath, .stateDirectory = stateDirectory, .installRoot = updateRoot, .runningExecutable = *runningExecutable, .currentCore = corePathResolved, .releaseManifestPath = runningManifest ? runningManifest->root / "manifest.json" : std::filesystem::path{}, .officialFeedUrl = std::string{Echoion::Standalone::UpdateBuildDefaults::FeedUrl}, .officialPublicKeysJson = std::string{ Echoion::Standalone::UpdateBuildDefaults::PublicKeysJson}, .runtimeVersion = runtimeVersion, .apiVersion = Echoion::Api::VERSION_STRING, .toolchainAbi = std::string{ Echoion::Standalone::UpdateBuildDefaults::ToolchainAbi}, .incomingDirectory = updaterIncomingDirectory(updateRoot, stateDirectory)}, Echoion::Standalone::UpdateService::Hooks{ .replaceCore = [&loader](const std::filesystem::path& path) { return loader.hotReload(path); }, .managePlugins = [&loader](const std::string& request) -> Echoion::Api::Result { if (auto loadedCore = loader.getCore()) { return loadedCore->managePluginsJson(request); } return Echoion::Api::fail( Echoion::Api::ErrorCode::ServiceUnavailable, "Core is not available"); }, .manageRuntime = [updaterExecutable, updateRoot](const std::string& request) { return invokeRuntimeHelper(updaterExecutable, updateRoot, request); }, .playbackActive = [&loader] { auto loadedCore = loader.getCore(); if (!loadedCore) { return false; } auto playback = loadedCore->getPlaybackSummary(); return playback && playback->isPlaying && playback->currentTrack.has_value(); }, .coreVersion = [&loader] { if (auto loadedCore = loader.getCore()) { return loadedCore->getVersion(); } return std::string{}; }}); if (auto started = updateService->start(); !started) { Void::Log::error("main", "Updater disabled: {}", started.error().message); updateService.reset(); } else { interface->setHostControlHandler( [service = updateService.get()](const std::string& method, const std::string& request) { return service->handle(method, request); }); } core->triggerAutoConnect(); core.reset(); auto releaseWatcher = std::make_unique(); releaseWatcher->watch( releaseTriggerPath, [](const Void::FileSystem::FileWatcher::Event& event) { if (event.exists) { requestUpdate(); } }); Void::Log::info("main", "Watching runtime update trigger {}", releaseTriggerPath.string()); if (std::filesystem::is_regular_file(releaseTriggerPath)) { requestUpdate(); } if (!std::filesystem::is_regular_file(installRoot / "manifest.json")) { // Compatibility mode for development. Production release bundles use // transactional daemon re-exec instead of replacing Core in isolation. loader.enableAutoReload(); } else { Void::Log::info( "main", "{}", "Core auto-reload is disabled for an installed release payload"); } Void::Log::info("main", "Echoion standalone running. Ctrl-C to stop."); std::optional healthVersion; if (const char* version = std::getenv("ECHOION_REEXEC_VERSION")) { healthVersion = version; Void::Log::info("main", "Release {} entered its 30 second health check", *healthVersion); } auto healthDeadline = std::chrono::steady_clock::now() + std::chrono::seconds{30}; std::optional pendingRelease; std::filesystem::path checkpointPath; bool stopRequested = false; while (!stopRequested && !pendingRelease) { if (updateService) { updateService->processPendingHostActions(); } if (healthVersion && std::chrono::steady_clock::now() >= healthDeadline) { bool committed = true; const auto handoff = readRuntimeHandoff(activationHandoff, updateRoot); if (handoff && handoff->state == "pending" && handoff->version == *healthVersion) { Void::Json::Value operation = Void::Json::object(); operation.as_object().emplace_back("action", Void::Json::Value{"commit"}); operation.as_object().emplace_back( "version", Void::Json::Value{*healthVersion}); operation.as_object().emplace_back( "retainHealthyVersions", Void::Json::Value{static_cast( handoff->retainHealthyVersions)}); auto result = invokeRuntimeHelper(updaterExecutable, updateRoot, Void::Json::serialize(operation)); if (!result) { committed = false; Void::Log::error("main", "Cannot confirm runtime {} health: {}", *healthVersion, result.error().message); } } if (committed) { std::ignore = Void::FileSystem::atomic_write( stateDirectory / "release-health", *healthVersion); std::ignore = Void::FileSystem::remove_path( stateDirectory / "release-transaction"); std::ignore = Void::FileSystem::remove_path(stateDirectory / "failed-release"); Void::Log::info("main", "Release {} passed its health check", *healthVersion); healthVersion.reset(); ::unsetenv("ECHOION_REEXEC_VERSION"); } else { healthDeadline = std::chrono::steady_clock::now() + std::chrono::seconds{5}; } } if (g_updateRequested.exchange(false)) { auto manifestPath = releaseTriggerPath; if (releaseTriggerIsHandoff) { auto handoff = readRuntimeHandoff(releaseTriggerPath, updateRoot); if (!handoff) { Void::Log::error("main", "runtime activation handoff is invalid"); continue; } if (handoff->version == runtimeVersion) { continue; } manifestPath = handoff->manifestPath; } auto manifest = Echoion::Standalone::ReleaseManifest::load(manifestPath); if (!manifest) { Void::Log::error("main", "release rejected: {}", manifest.error().message); continue; } if (manifest->version == runtimeVersion) { continue; } if (auto failed = Void::FileSystem::read_file(stateDirectory / "failed-release"); failed && *failed == manifest->version) { Void::Log::error( "main", "Release {} was previously rolled back; publish a new " "version to retry", manifest->version); continue; } auto validation = Void::Process::run( *runningExecutable, {"--validate-release", manifestPath.string()}, {}, std::chrono::seconds{30}); if (!validation || validation->exit_code != 0) { Void::Log::error("main", "release validation failed: {}", validation ? validation->err : validation.error().message()); continue; } checkpointPath = stateDirectory / "restart-state.bin"; if (auto checkpoint = loader.checkpoint(checkpointPath); !checkpoint) { Void::Log::error("main", "release checkpoint failed: {}", checkpoint.error().message); continue; } pendingRelease = std::move(*manifest); continue; } auto observedSignal = signalWatcher.wait(std::chrono::milliseconds{250}); if (!observedSignal) { Void::Log::error("main", "signal watcher failed: {}", observedSignal.error().message()); stopRequested = true; } else if (observedSignal->has_value()) { stopRequested = true; } } releaseWatcher.reset(); Void::Log::info("main", "{}", pendingRelease ? "Applying validated release..." : "Shutting down..."); interface->setHostControlHandler({}); if (updateService) { updateService->stop(); } updateService.reset(); loader.disableAutoReload(); (void)interface->disconnectFromServer(); interface->quiesceEventCallbacks(); (void)loader.unload(); (void)interface->shutdown(); if (pendingRelease) { if (auto transaction = Void::FileSystem::atomic_write( stateDirectory / "release-transaction", pendingRelease->version); !transaction) { Void::Log::error("main", "cannot record release transaction: {}", transaction.error().message()); return 1; } const auto pendingRoot = Echoion::Standalone::deriveInstallRoot(pendingRelease->executable); const auto pendingHome = releaseTriggerIsHandoff ? updateRoot / "current" : pendingRoot; const auto pendingRootString = pendingHome.string(); const auto pendingCoreString = pendingRelease->core.string(); if (::setenv("ECHOION_HOME", pendingRootString.c_str(), 1) != 0 || ::setenv("ECHOION_CORE_PATH", pendingCoreString.c_str(), 1) != 0 || ::setenv("ECHOION_REEXEC_VERSION", pendingRelease->version.c_str(), 1) != 0) { Void::Log::error("main", "cannot export pending release paths"); return 1; } std::vector arguments; arguments.reserve(static_cast(argc) + 2); for (int index = 1; index < argc; ++index) { const std::string_view argument{argv[index]}; if (argument == "--restore-state") { ++index; continue; } arguments.emplace_back(argument); } arguments.emplace_back("--restore-state"); arguments.push_back(checkpointPath.string()); if (auto result = Void::Process::reexec(pendingRelease->executable, arguments); !result) { Void::Log::error("main", "release re-exec failed: {}", result.error().message()); return 1; } } return 0; }