Skip to content
Repos

mologram

C++ 5.4 KB144 lines Opens in site

Directory Raw Download

// Daemon respawn (OPS-02, D-13): when the daemon dies, the UI relaunches it every second and the client reconnects. Real processes:
// the daemon is mologramd --fake started through DaemonLauncher, killed with SIGKILL, and brought back by DaemonSupervisor.
#include <dirent.h>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>

#include <chrono>
#include <filesystem>
#include <fstream>
#include <future>
#include <thread>

#include "tttest.hpp"
#include "ptychild.hpp"
#include "mologram/DaemonLauncher.hpp"
#include "mologram/DaemonSupervisor.hpp"
#include "mologram/RemoteService.hpp"

using namespace mologram;
using ptytest::PtyChild;
using ptytest::binDir;

namespace {

struct TempDir {
  std::string path;
  TempDir() { char t[] = "/tmp/mologram-respawn-XXXXXX"; path = mkdtemp(t); }
  ~TempDir() { std::error_code ec; std::filesystem::remove_all(path, ec); }
};

/// Pids of mologramd processes serving exactly this socket (found by scanning /proc, so nothing else can be hit).
std::vector<pid_t> daemonPids(const std::string& sock) {
  std::vector<pid_t> out;
  DIR* d = ::opendir("/proc");
  if (!d) return out;
  while (dirent* e = ::readdir(d)) {
    if (e->d_name[0] < '0' || e->d_name[0] > '9') continue;
    std::ifstream f(std::string("/proc/") + e->d_name + "/cmdline", std::ios::binary);
    std::string cmd((std::istreambuf_iterator<char>(f)), std::istreambuf_iterator<char>());
    if (cmd.find("mologramd") != std::string::npos && cmd.find(sock) != std::string::npos) out.push_back((pid_t)std::atoi(e->d_name));
  }
  ::closedir(d);
  return out;
}

bool isLive(pid_t p) {
  std::ifstream f("/proc/" + std::to_string(p) + "/stat");
  std::string line;
  std::getline(f, line);
  size_t close = line.rfind(')');
  return close != std::string::npos && close + 2 < line.size() && line[close + 2] != 'Z';  // a zombie is dead
}

std::vector<pid_t> livePids(const std::string& sock) {
  std::vector<pid_t> v;
  for (pid_t p : daemonPids(sock)) if (isLive(p)) v.push_back(p);
  return v;
}

template <class F>
bool waitFor(F pred, int ms = 20000) {
  auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
  while (std::chrono::steady_clock::now() < end) {
    if (pred()) return true;
    std::this_thread::sleep_for(std::chrono::milliseconds(20));
  }
  return pred();
}

void killAll(const std::string& sock) {
  for (pid_t p : livePids(sock)) ::kill(p, SIGKILL);
}

}  // namespace

TEST_CASE("the supervisor relaunches a killed daemon and the client reconnects without help", "[process][respawn][integration]") {
  TempDir d;
  std::string sock = d.path + "/m.sock";
  REQUIRE(DaemonLauncher::ensure(sock, {"--fake"}).empty());
  auto first = livePids(sock);
  REQUIRE(first.size() == 1);
  RemoteService remote(sock);
  remote.start();
  REQUIRE(remote.waitConnected(nullptr));
  {
    DaemonSupervisor sup(remote, sock, {"--fake"});
    ::kill(first[0], SIGKILL);
    CHECK(waitFor([&] { return !remote.connected(); }));
    CHECK(waitFor([&] { return remote.connected(); }));  // the supervisor started a new daemon, the client reconnected
    CHECK(waitFor([&] { return sup.restarts() >= 1; }));  // the client can reconnect a moment before the supervisor counts the restart
    auto second = livePids(sock);
    REQUIRE(second.size() == 1);
    CHECK(second[0] != first[0]);
    auto pr = std::make_shared<std::promise<RpcResult>>();
    auto fu = pr->get_future();
    remote.call("hello", js::Value(js::Object{}), [pr](const RpcResult& r) { pr->set_value(r); });
    REQUIRE(fu.wait_for(std::chrono::seconds(8)) == std::future_status::ready);
    CHECK(fu.get().ok);
  }
  killAll(sock);
}

TEST_CASE("the supervisor leaves a healthy daemon alone and stops promptly when destroyed", "[process][respawn][integration]") {
  TempDir d;
  std::string sock = d.path + "/m.sock";
  REQUIRE(DaemonLauncher::ensure(sock, {"--fake"}).empty());
  RemoteService remote(sock);
  remote.start();
  REQUIRE(remote.waitConnected(nullptr));
  auto before = livePids(sock);
  {
    DaemonSupervisor sup(remote, sock, {"--fake"});
    std::this_thread::sleep_for(std::chrono::milliseconds(2500));  // two supervisor rounds
    CHECK_EQ((int)sup.restarts(), 0);
  }
  CHECK(livePids(sock) == before);
  killAll(sock);
}

TEST_CASE("a UI process in a terminal keeps its draft and open chat when its daemon is killed and comes back", "[process][respawn][integration]") {
  TempDir d;
  std::string sock = d.path + "/m.sock";
  std::string cfg = d.path + "/cfg.json";
  { std::ofstream f(cfg); f << "{\"api_id\":1,\"api_hash\":\"x\",\"phone\":\"+1\",\"data_dir\":\"" << d.path << "\"}"; }
  PtyChild c;
  REQUIRE(c.start({binDir() + "/mologram", "--chat", "user:100", "--fake-daemon", "--socket", sock, "--config", cfg}));
  REQUIRE(c.waitFor("Message 40 in Alice"));
  c.write("my unsent draft");
  REQUIRE(c.waitFor("my unsent draft"));
  auto first = livePids(sock);
  REQUIRE(first.size() == 1);
  ::kill(first[0], SIGKILL);
  // the supervisor starts a new daemon; wait for a different live pid
  REQUIRE(waitFor([&] { auto now = livePids(sock); return now.size() == 1 && now[0] != first[0]; }, 25000));
  c.pump(2500);  // let the client reconnect and the chat reload
  CHECK(c.has("my unsent draft"));  // the draft survived the restart
  CHECK(c.has("Message 40 in Alice"));  // the conversation is open again with its history
  c.write("\x11");
  int status = c.wait(12000);
  CHECK(status != -1);
  CHECK(ptytest::restored(c.out));
  killAll(sock);
}
28.7ms