nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
main.cc
Go to the documentation of this file.
1#include <algorithm>
2#include <atomic>
3#include <chrono>
4#include <csignal>
5#include <cstdint>
6#include <exception>
7#include <iostream>
8#include <memory>
9#include <optional>
10#include <string>
11#include <string_view>
12#include <utility>
13#include <vector>
14
15#include "absl/status/statusor.h"
16#include "absl/strings/ascii.h"
17#include "absl/strings/numbers.h"
18#include "absl/strings/str_cat.h"
19#include "absl/time/clock.h"
20#include "absl/time/time.h"
21#include "asio/io_context.hpp"
22#include "asio/post.hpp"
23#include "asio/signal_set.hpp"
24#include "asio/ssl/context.hpp"
25#include "asio/steady_timer.hpp"
26#include "asio/thread_pool.hpp"
27#include "content/content.h"
28#include "prometheus/exposer.h"
29#include "protocol/settings.h"
30#include "protocol/tls.h"
31#include "protocol/version.h"
32#include "server/consul.h"
33#include "server/database.h"
34#include "server/metrics.h"
35#include "server/players.h"
36#include "server/redis.h"
37#include "server/server.h"
38#include "server/storyteller.h"
39#include "server/tick.h"
40#include "server/tokens.h"
41#include "server/tracing.h"
42
43namespace {
44
45std::optional<uint16_t> ParsePort(std::string_view text) {
46 int port = 0;
47 if (!absl::SimpleAtoi(text, &port) || port < 1 || port > 65535) {
48 return std::nullopt;
49 }
50 return static_cast<uint16_t>(port);
51}
52
53} // namespace
54
55int main(int argc, char* argv[]) {
56 std::cout << "nanommo server: version " << nanommo::kVersion << std::endl;
57 constexpr int kTicksPerSecond = 20;
58 const absl::StatusOr<std::chrono::nanoseconds> interval =
59 nanommo::TickInterval(kTicksPerSecond);
60 if (!interval.ok()) {
61 std::cerr << "nanommo server: " << interval.status() << "\n";
62 return 1;
63 }
64 const std::optional<uint16_t> port =
65 argc > 1 ? ParsePort(argv[1]) : uint16_t{7777};
66 if (!port) {
67 std::cerr
68 << "nanommo server: the port should be a number from 1 to 65535, not "
69 << argv[1] << "\n";
70 return 1;
71 }
72 const std::string metrics_setting =
73 nanommo::Setting("NANOMMO_METRICS_PORT", "9464");
74 const std::optional<uint16_t> metrics_port = ParsePort(metrics_setting);
75 if (!metrics_port) {
76 std::cerr << "nanommo server: NANOMMO_METRICS_PORT should be a number from "
77 "1 to 65535, not "
78 << metrics_setting << "\n";
79 return 1;
80 }
81
82 const std::string name = nanommo::Setting("NANOMMO_WORLD", "Ember");
83 if (name.empty() || name.size() > 16 ||
84 !std::ranges::all_of(name, absl::ascii_isalnum)) {
85 std::cerr << "nanommo server: NANOMMO_WORLD should be up to 16 letters "
86 "and digits, not "
87 << name << "\n";
88 return 1;
89 }
90 uint32_t seed = 1;
91 const std::string seed_setting = nanommo::Setting("NANOMMO_WORLD_SEED", "1");
92 if (!absl::SimpleAtoi(seed_setting, &seed)) {
93 std::cerr << "nanommo server: NANOMMO_WORLD_SEED should be a whole number "
94 "from 0 to 4294967295, not "
95 << seed_setting << "\n";
96 return 1;
97 }
98 const absl::StatusOr<nanommo::Content> content =
99 nanommo::ReadContent(nanommo::FileSetting("NANOMMO_CONTENT", "content"));
100 if (!content.ok()) {
101 std::cerr << "nanommo server: " << content.status() << "\n";
102 return 1;
103 }
104
105 absl::StatusOr<asio::ssl::context> tls = nanommo::ServerTls(
106 nanommo::FileSetting("NANOMMO_TLS_CERTIFICATE", "tls/server.crt"),
107 nanommo::FileSetting("NANOMMO_TLS_KEY", "tls/server.key"));
108 if (!tls.ok()) {
109 std::cerr << "nanommo server: " << tls.status() << "\n";
110 return 1;
111 }
112
113 nanommo::Metrics metrics;
114 // civetweb throws when the port's taken, as by another world on this
115 // machine, which would end the server without a word on why.
116 std::optional<prometheus::Exposer> exposer;
117 try {
118 exposer.emplace("0.0.0.0:" + std::to_string(*metrics_port));
119 } catch (const std::exception& error) {
120 std::cerr << "nanommo server: couldn't serve metrics on port "
121 << *metrics_port << " (" << error.what()
122 << "). Is another server running here? Another world needs a "
123 "port of its own, and NANOMMO_METRICS_PORT too\n";
124 return 1;
125 }
126 exposer->RegisterCollectable(metrics.registry());
127
128 absl::StatusOr<std::unique_ptr<nanommo::Database>> database_or =
130 nanommo::Setting("NANOMMO_MYSQL_HOST", "127.0.0.1"), "nanommo",
131 nanommo::Setting("NANOMMO_MYSQL_PASSWORD", "nanommo"), "nanommo");
132 if (!database_or.ok()) {
133 std::cerr << "nanommo server: " << database_or.status() << "\n";
134 return 1;
135 }
136 const std::unique_ptr<nanommo::Database> database = *std::move(database_or);
137 absl::StatusOr<std::unique_ptr<nanommo::Redis>> redis_or =
139 nanommo::Setting("NANOMMO_REDIS_HOST", "127.0.0.1"));
140 if (!redis_or.ok()) {
141 std::cerr << "nanommo server: " << redis_or.status() << "\n";
142 return 1;
143 }
144 const std::unique_ptr<nanommo::Redis> redis = *std::move(redis_or);
145 nanommo::Tokens tokens(*redis);
146 nanommo::Players players(*database, *redis);
147 nanommo::Guilds guilds(*database, *redis);
148 nanommo::Events events(*redis);
149
150 asio::io_context io;
151 nanommo::Storyteller storyteller(
152 io, nanommo::Setting("NANOMMO_STORYTELLER_HOST", "127.0.0.1"));
153 absl::StatusOr<std::unique_ptr<nanommo::Server>> server_or =
154 nanommo::Server::Create(io, *port, *tls, *interval, name, seed, *content,
155 metrics, tokens, players, guilds, events,
156 storyteller);
157 if (!server_or.ok()) {
158 std::cerr << "nanommo server: " << server_or.status() << "\n";
159 return 1;
160 }
161 const std::unique_ptr<nanommo::Server> server = *std::move(server_or);
162 std::cout << "nanommo server: " << name << ", listening on port " << *port
163 << ", " << kTicksPerSecond << " ticks/s, "
164 << absl::FormatDuration(absl::FromChrono(*interval)) << " per tick"
165 << ", world seed " << seed << std::endl;
166 const uint64_t content_hash = nanommo::ClientHash(*content);
167 std::cout << "nanommo server: content "
168 << absl::StrCat(absl::Hex(content_hash, absl::kZeroPad16))
169 << std::endl;
170 std::cout << "nanommo server: metrics on port " << *metrics_port
171 << ", at /metrics" << std::endl;
172
173 nanommo::Consul consul(nanommo::Setting("NANOMMO_CONSUL_HOST", "127.0.0.1"));
174 nanommo::WorldRegistration registration{
175 .name = name,
176 .public_host = nanommo::Setting("NANOMMO_PUBLIC_HOST", "localhost"),
177 .port = *port,
178 .metrics_port = *metrics_port,
179 .content = content_hash,
180 .started = absl::ToUnixSeconds(absl::Now()),
181 };
182 const std::string instance = nanommo::InstanceId(registration);
183 // As the instance, as two of a world's can run at once, to an OpenTelemetry
184 // collector, such as Alloy, when there's one.
185 const std::string collector = nanommo::Setting("NANOMMO_OTLP_ENDPOINT", "");
186 if (!collector.empty()) {
187 nanommo::StartTracing(instance, nanommo::PostTo(collector),
188 metrics.registry().get());
189 std::cout << "nanommo server: sending spans to " << collector << std::endl;
190 }
191 // Consul gets its own thread, so that a slow answer can't hold up a tick.
192 asio::thread_pool consul_thread(1);
193 // A beat still waiting on Consul is enough, so that beats can't pile up.
194 std::atomic<bool> waiting = false;
195 std::optional<int> listed;
196 std::string said;
197 constexpr std::chrono::seconds kHeartbeat{2};
198 asio::steady_timer heartbeat(io);
199 // The lambda gets its own object as its first parameter, self, so that it
200 // can wait on the timer again. It names its return type, which async_wait
201 // checks, so that it doesn't depend on its early return coming first.
202 auto beat = [&](this auto self, std::error_code error) -> void {
203 if (error) {
204 return;
205 }
206 registration.players = server->players();
207 if (!waiting.exchange(true)) {
208 asio::post(
209 consul_thread, [&consul, &listed, &said, &waiting, registration] {
210 absl::Status status = absl::OkStatus();
211 if (listed != registration.players) {
212 status = consul.Register(registration);
213 }
214 // Registering again keeps a critical check critical, so each beat
215 // passes it.
216 if (status.ok()) {
217 status = consul.Pass(nanommo::InstanceId(registration));
218 }
219 if (status.ok()) {
220 listed = registration.players;
221 } else {
222 // Consul forgets the worlds when it restarts, so the next beat
223 // registers ours again.
224 listed.reset();
225 }
226 const std::string news = status.ok()
227 ? "registered with Consul as " +
228 nanommo::InstanceId(registration)
229 : status.ToString();
230 // Once when it changes, not with each heartbeat.
231 if (news != said) {
232 said = news;
233 std::cout << "nanommo server: " << news << std::endl;
234 }
235 waiting = false;
236 });
237 }
238 heartbeat.expires_after(kHeartbeat);
239 heartbeat.async_wait(self);
240 };
241 beat({});
242
243 // Each client leaves once it's in the next instance, within a few seconds.
244 constexpr std::chrono::seconds kHandOverTime{10};
245 asio::steady_timer leaving(io);
246 std::chrono::steady_clock::time_point deadline;
247 auto wait = [&](this auto self, std::error_code) -> void {
248 if (server->players() == 0 || std::chrono::steady_clock::now() > deadline) {
249 io.stop();
250 return;
251 }
252 leaving.expires_after(std::chrono::milliseconds(100));
253 leaving.async_wait(self);
254 };
255
256 // As process one in a container, SIGTERM does nothing unless we handle it.
257 asio::signal_set signals(io, SIGINT, SIGTERM);
258 signals.async_wait([&](std::error_code, int) {
259 heartbeat.cancel();
260 consul_thread.join();
261 const absl::Status deregistered = consul.Deregister(instance);
262 if (!deregistered.ok()) {
263 std::cerr << "nanommo server: " << deregistered << "\n";
264 }
265 // A deploy starts the world's next instance before it stops this one, so
266 // with us gone from Consul, the world's newest instance is the next one.
267 const absl::StatusOr<std::vector<nanommo::protocol::WorldListing>> worlds =
268 consul.Worlds();
269 const nanommo::protocol::WorldListing* next = nullptr;
270 if (worlds.ok()) {
271 const auto found = std::ranges::find(
272 *worlds, name, &nanommo::protocol::WorldListing::name);
273 next = found != worlds->end() ? &*found : nullptr;
274 }
275 if (next == nullptr || server->players() == 0) {
276 io.stop();
277 return;
278 }
279 const int told =
280 server->HandOver(next->host(), static_cast<uint16_t>(next->port()));
281 std::cout << "nanommo server: handing " << told
282 << (told == 1 ? " player" : " players") << " over to "
283 << next->host() << ":" << next->port() << std::endl;
284 deadline = std::chrono::steady_clock::now() + kHandOverTime;
285 wait({});
286 });
287 io.run();
289 std::cout << "nanommo server: stopped" << std::endl;
290 return 0;
291}
absl::Status Pass(const std::string &instance) const
Definition consul.cc:106
absl::Status Register(const WorldRegistration &world) const
Definition consul.cc:80
absl::StatusOr< std::vector< protocol::WorldListing > > Worlds() const
Definition consul.cc:114
absl::Status Deregister(const std::string &instance) const
Definition consul.cc:110
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
const std::shared_ptr< prometheus::Registry > & registry() const
Definition metrics.h:50
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
static absl::StatusOr< std::unique_ptr< Server > > Create(asio::io_context &io, uint16_t port, asio::ssl::context &tls, std::chrono::nanoseconds interval, std::string name, uint32_t seed, const Content &content, Metrics &metrics, Tokens &tokens, Players &players, Guilds &guilds, Events &events, Storyteller &storyteller)
Definition server.cc:124
int main()
Definition login_main.cc:28
std::string Setting(const char *name, const std::string &fallback)
Definition settings.h:9
void StopTracing()
Definition tracing.cc:387
std::string InstanceId(const WorldRegistration &world)
Definition consul.cc:76
absl::StatusOr< std::chrono::nanoseconds > TickInterval(int ticks_per_second)
Definition tick.cc:9
uint64_t ClientHash(const Content &content)
Definition content.cc:232
SendSpans PostTo(const std::string &endpoint)
Definition tracing.cc:351
void StartTracing(std::string service, SendSpans send, prometheus::Registry *registry)
Definition tracing.cc:371
absl::StatusOr< asio::ssl::context > ServerTls(const std::string &certificate, const std::string &key)
Definition tls.cc:26
std::string FileSetting(const char *name, const std::string &path)
Definition settings.cc:22
absl::StatusOr< Content > ReadContent(const std::string &folder)
Reads each file in the folder, or says which file is wrong, and where.
Definition content.cc:64
A world, as it registers with Consul.
Definition consul.h:16