nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
saver_main.cc
Go to the documentation of this file.
1#include <chrono>
2#include <csignal>
3#include <cstdint>
4#include <iostream>
5#include <memory>
6#include <string>
7#include <utility>
8
9#include "absl/status/statusor.h"
10#include "absl/time/clock.h"
11#include "absl/time/time.h"
12#include "asio/io_context.hpp"
13#include "asio/signal_set.hpp"
14#include "asio/steady_timer.hpp"
15#include "prometheus/exposer.h"
16#include "prometheus/gauge.h"
17#include "prometheus/registry.h"
18#include "protocol/settings.h"
19#include "server/database.h"
20#include "server/players.h"
21#include "server/redis.h"
22#include "server/tracing.h"
23
24namespace {
25
26constexpr std::chrono::seconds kInterval(5);
27constexpr uint16_t kMetricsPort = 9466;
28
29// What the saver's metrics say.
30struct Gauges {
31 prometheus::Gauge& duplicates;
32 prometheus::Gauge& flushed;
33 prometheus::Gauge& unsaved;
34};
35
36void Flush(nanommo::Players& players, const Gauges& gauges) {
37 const auto start = std::chrono::steady_clock::now();
38 const absl::StatusOr<int> saved = players.Flush();
39 if (!saved.ok()) {
40 std::cerr << "nanommo saver: " << saved.status() << "\n";
41 } else {
42 // When MySQL last had everything Redis had as the flush began, which an
43 // alert can tell the age of, whether the saver's failing or stuck. One
44 // that's gone takes its gauge with it, which up says.
45 gauges.flushed.Set(absl::ToDoubleSeconds(absl::Now() - absl::UnixEpoch()));
46 if (*saved > 0) {
47 std::cout << "nanommo saver: saved " << *saved << " players in "
48 << absl::FormatDuration(absl::FromChrono(
49 std::chrono::steady_clock::now() - start))
50 << std::endl;
51 }
52 }
53 // Those who changed since, for the next flush.
54 const absl::StatusOr<int> waiting = players.Unsaved();
55 if (waiting.ok()) {
56 gauges.unsaved.Set(*waiting);
57 }
58 // Two items with one serial are an item and its copy, which the alerts
59 // watch for.
60 const absl::StatusOr<int> twice = players.Duplicates();
61 if (!twice.ok()) {
62 std::cerr << "nanommo saver: " << twice.status() << "\n";
63 return;
64 }
65 gauges.duplicates.Set(*twice);
66}
67
68} // namespace
69
70int main() {
71 absl::StatusOr<std::unique_ptr<nanommo::Database>> database_or =
73 nanommo::Setting("NANOMMO_MYSQL_HOST", "127.0.0.1"), "nanommo",
74 nanommo::Setting("NANOMMO_MYSQL_PASSWORD", "nanommo"), "nanommo");
75 if (!database_or.ok()) {
76 std::cerr << "nanommo saver: " << database_or.status() << "\n";
77 return 1;
78 }
79 const std::unique_ptr<nanommo::Database> database = *std::move(database_or);
80 absl::StatusOr<std::unique_ptr<nanommo::Redis>> redis_or =
82 nanommo::Setting("NANOMMO_REDIS_HOST", "127.0.0.1"));
83 if (!redis_or.ok()) {
84 std::cerr << "nanommo saver: " << redis_or.status() << "\n";
85 return 1;
86 }
87 const std::unique_ptr<nanommo::Redis> redis = *std::move(redis_or);
88 nanommo::Players players(*database, *redis);
89 std::cout << "nanommo saver: saving to MySQL every "
90 << absl::FormatDuration(absl::FromChrono(kInterval)) << std::endl;
91
92 auto registry = std::make_shared<prometheus::Registry>();
93 const Gauges gauges{
94 .duplicates = prometheus::BuildGauge()
95 .Name("nanommo_duplicate_items")
96 .Help("Serials that more than one item in MySQL has")
97 .Register(*registry)
98 .Add({}),
99 .flushed = prometheus::BuildGauge()
100 .Name("nanommo_saver_flushed_timestamp_seconds")
101 .Help("When the last flush that saved everyone ended")
102 .Register(*registry)
103 .Add({}),
104 .unsaved = prometheus::BuildGauge()
105 .Name("nanommo_unsaved_players")
106 .Help("Players in Redis waiting for the next flush")
107 .Register(*registry)
108 .Add({}),
109 };
110 prometheus::Exposer exposer("0.0.0.0:" + std::to_string(kMetricsPort));
111 exposer.RegisterCollectable(registry);
112 // It has as long to make its first good flush as it has for each after,
113 // from now.
114 gauges.flushed.Set(absl::ToDoubleSeconds(absl::Now() - absl::UnixEpoch()));
115
116 // The trades it saves carry on their traces, to an OpenTelemetry collector,
117 // such as Alloy, when there's one.
118 const std::string collector = nanommo::Setting("NANOMMO_OTLP_ENDPOINT", "");
119 if (!collector.empty()) {
120 nanommo::StartTracing("saver", nanommo::PostTo(collector), registry.get());
121 std::cout << "nanommo saver: sending spans to " << collector << std::endl;
122 }
123
124 asio::io_context io;
125 asio::steady_timer timer(io, kInterval);
126 // self is the lambda, which waits on the timer again, with its return type
127 // named, as async_wait checks it.
128 auto tick = [&](this auto self, std::error_code error) -> void {
129 if (error) {
130 return;
131 }
132 Flush(players, gauges);
133 timer.expires_at(timer.expiry() + kInterval);
134 timer.async_wait(self);
135 };
136 timer.async_wait(tick);
137
138 asio::signal_set signals(io, SIGINT, SIGTERM);
139 signals.async_wait([&io](std::error_code, int) { io.stop(); });
140 io.run();
141 Flush(players, gauges);
143 std::cout << "nanommo saver: saved what was left, and stopped" << std::endl;
144 return 0;
145}
static absl::StatusOr< std::unique_ptr< Database > > Create(const std::string &host, const std::string &user, const std::string &password, const std::string &name, MysqlTimeouts timeouts={})
Definition database.cc:106
absl::StatusOr< int > Duplicates()
Definition players.cc:913
absl::StatusOr< int > Flush()
Definition players.cc:578
absl::StatusOr< int > Unsaved()
Definition players.cc:898
static absl::StatusOr< std::unique_ptr< Redis > > Create(const std::string &host, int port=6379, RedisTimeouts timeouts={})
Connects to Redis, or returns why it couldn't.
Definition redis.cc:121
std::string Setting(const char *name, const std::string &fallback)
Definition settings.h:9
void StopTracing()
Definition tracing.cc:387
SendSpans PostTo(const std::string &endpoint)
Definition tracing.cc:351
void StartTracing(std::string service, SendSpans send, prometheus::Registry *registry)
Definition tracing.cc:371
int main()
Definition saver_main.cc:70