Signed-off-by: faumaray <faumaray@gmail.com>
This commit is contained in:
faumaray committed 2026-07-25 23:44:48 +03:00
1 parent 11850b1a8d
commit 46ff4068cf
9 files changed
+4657 -96

No files matched your search

+514 -85
View File
@@ -5,48 +5,47 @@
#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 <CoreInterface.hpp>
#include <Void/Data/Json.hpp>
#include <Void/Log/Log.hpp>
#include <Void/Stacktrace/Stacktrace.hpp>
#include <Void/System/FileWatcher.hpp>
#include <Void/System/Path.hpp>
#include <Void/System/Process.hpp>
#include <Void/System/SignalWatcher.hpp>
#include <Void/TeamSpeak/Identity.hpp>
#include <Void/Update/Update.hpp>
#include <algorithm>
#include <array>
#include <atomic>
#include <condition_variable>
#include <csignal>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <exception>
#include <filesystem>
#include <iostream>
#include <memory>
#include <mutex>
#include <optional>
#include <string>
#include <string_view>
#include <system_error>
#include <thread>
#include <vector>
#ifndef _WIN32
#include <unistd.h>
#endif
namespace
{
std::atomic<bool> g_stop{false};
std::atomic<bool> g_updateRequested{false};
std::condition_variable g_cv;
std::mutex g_mu;
void onSignal(int)
{
g_stop = true;
g_cv.notify_all();
}
void requestUpdate()
{
g_updateRequested = true;
g_cv.notify_all();
}
void requestUpdate() { g_updateRequested = true; }
std::optional<std::string_view> argumentValue(int argc, char** argv,
std::string_view name)
@@ -101,6 +100,255 @@ namespace
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<std::uint32_t>
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<std::uint32_t>(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<RuntimeHandoff>
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<Echoion::Standalone::ReleaseManifest>
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<std::string>
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<std::string> 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<std::string> 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")) {
@@ -298,6 +546,7 @@ int main(int argc, char** argv)
}
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");
@@ -334,6 +583,13 @@ int main(int argc, char** argv)
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(
@@ -348,9 +604,26 @@ int main(int argc, char** argv)
requestedRestore ? std::optional{absolutePath(*requestedRestore)}
: std::nullopt;
const auto requestedManifest = environmentPath("ECHOION_RELEASE_MANIFEST");
const std::optional<std::filesystem::path> releaseManifestPath =
requestedManifest ? std::optional{absolutePath(*requestedManifest)}
: std::nullopt;
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();
@@ -371,8 +644,17 @@ int main(int argc, char** argv)
loader.setConfigPath(cfgPath);
const auto executableDirectory = runningExecutable->parent_path();
const auto corePathResolved = Echoion::Standalone::resolveCorePath(
installRoot, executableDirectory, environmentPath("ECHOION_CORE_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)) {
@@ -423,21 +705,95 @@ int main(int argc, char** argv)
}
});
core->triggerAutoConnect();
std::unique_ptr<Void::FileSystem::FileWatcher> releaseWatcher;
if (releaseManifestPath) {
releaseWatcher = std::make_unique<Void::FileSystem::FileWatcher>();
releaseWatcher->watch(
*releaseManifestPath,
[](const Void::FileSystem::FileWatcher::Event& event) {
if (event.exists) {
requestUpdate();
const auto updaterExecutable =
runningExecutable->parent_path() / "echoion-updater";
auto updateService = std::make_unique<Echoion::Standalone::UpdateService>(
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<std::string> {
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);
});
Void::Log::info("main", "Watching release manifest {}",
releaseManifestPath->string());
} else if (!std::filesystem::is_regular_file(installRoot /
"manifest.json")) {
}
core->triggerAutoConnect();
core.reset();
auto releaseWatcher = std::make_unique<Void::FileSystem::FileWatcher>();
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();
@@ -447,72 +803,143 @@ int main(int argc, char** argv)
"Core auto-reload is disabled for an installed release payload");
}
std::signal(SIGINT, onSignal);
std::signal(SIGTERM, onSignal);
Void::Log::info("main", "Echoion standalone running. Ctrl-C to stop.");
std::optional<std::string> healthVersion;
if (const char* version = std::getenv("ECHOION_REEXEC_VERSION")) {
std::ignore = Void::FileSystem::atomic_write(
stateDirectory / "release-health", version);
std::ignore = Void::FileSystem::remove_path(stateDirectory /
"release-transaction");
std::ignore =
Void::FileSystem::remove_path(stateDirectory / "failed-release");
::unsetenv("ECHOION_REEXEC_VERSION");
Void::Log::info("main", "Release {} passed startup health check",
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<Echoion::Standalone::ReleaseManifest> pendingRelease;
std::filesystem::path checkpointPath;
while (!g_stop.load() && !pendingRelease) {
{
std::unique_lock<std::mutex> lock(g_mu);
g_cv.wait(lock,
[] { return g_stop.load() || g_updateRequested.load(); });
bool stopRequested = false;
while (!stopRequested && !pendingRelease) {
if (updateService) {
updateService->processPendingHostActions();
}
if (g_stop.load() || !releaseManifestPath) {
break;
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<long long>(
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};
}
}
g_updateRequested = false;
auto manifest =
Echoion::Standalone::ReleaseManifest::load(*releaseManifestPath);
if (!manifest) {
Void::Log::error("main", "release rejected: {}",
manifest.error().message);
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;
}
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 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;
}
auto validation = Void::Process::run(
*runningExecutable,
{"--validate-release", releaseManifestPath->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);
}
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();
@@ -529,7 +956,9 @@ int main(int argc, char** argv)
}
const auto pendingRoot =
Echoion::Standalone::deriveInstallRoot(pendingRelease->executable);
const auto pendingRootString = pendingRoot.string();
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 ||