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 <chrono>
3#include <csignal>
4#include <cstddef>
5#include <cstdint>
6#include <iostream>
7#include <memory>
8#include <optional>
9#include <random>
10#include <string>
11#include <string_view>
12#include <system_error>
13#include <utility>
14#include <vector>
15
16#include "absl/status/status.h"
17#include "absl/status/statusor.h"
18#include "absl/strings/numbers.h"
19#include "asio/io_context.hpp"
20#include "asio/ip/tcp.hpp"
21#include "asio/signal_set.hpp"
22#include "asio/ssl/context.hpp"
23#include "asio/steady_timer.hpp"
24#include "bot/backoff.h"
25#include "bot/bot.h"
26#include "bot/bot_metrics.h"
27#include "content/content.h"
28#include "prometheus/exposer.h"
29#include "protocol/clock.h"
31#include "protocol/nanommo.pb.h"
32#include "protocol/settings.h"
33#include "protocol/tls.h"
34#include "protocol/version.h"
35
36namespace {
37
38constexpr uint16_t kGamePort = 7777;
39constexpr uint16_t kLoginPort = 7778;
40constexpr uint16_t kMetricsPort = 9465;
41
42// Sixty frames a second, near enough. Sixteen doesn't divide the tick's
43// fifty, so the frames land all over the tick, like a client's would.
44constexpr std::chrono::milliseconds kFrame(16);
45
46// The world on kGamePort, which the bots play in.
47constexpr char kWorld[] = "Ember";
48
49// At war, how far either side of where new players come in each side waits,
50// and how far apart its bots stand, in metres.
51constexpr float kCamp = 8.0f;
52constexpr float kSpacing = 1.5f;
53
54// How long a bot that's logged in has to reach its world, and how long one
55// that's lost its world takes to notice, before it logs in again.
56constexpr std::chrono::seconds kGrace(5);
57
58// The most bots that log in again each second, as each waits for the login
59// server, and the swarm's other bots for it.
60constexpr int kRejoinsPerSecond = 5;
61
62// The login server's answer, or why there's none: it couldn't be reached, or
63// it said no.
64absl::StatusOr<nanommo::protocol::LoginReply> Ask(
65 const std::string& host, asio::ssl::context& tls,
66 const nanommo::protocol::LoginRequest& request) {
67 absl::StatusOr<nanommo::protocol::LoginReply> reply =
68 nanommo::LogIn(host, kLoginPort, tls, request);
69 if (reply.ok() && !reply->ok()) {
70 return absl::PermissionDeniedError(reply->error());
71 }
72 return reply;
73}
74
75// Logs bot `number` in, making its account the first time, and its
76// character in kWorld, named after it, and returns a token to enter as it.
77absl::StatusOr<std::string> LogIn(const std::string& host,
78 asio::ssl::context& tls, int number) {
79 const std::string name = "bot" + std::to_string(number);
80 nanommo::protocol::LoginRequest request;
81 request.set_username(name);
82 request.set_password("bot-password");
83 request.set_version(nanommo::kVersion);
84 absl::StatusOr<nanommo::protocol::LoginReply> reply = Ask(host, tls, request);
85 if (absl::IsPermissionDenied(reply.status())) {
86 request.set_new_account(true);
87 reply = Ask(host, tls, request);
88 }
89 if (!reply.ok()) {
90 return reply.status();
91 }
92 nanommo::protocol::LoginRequest next;
93 next.set_session(reply->session());
94 const auto mine = [](const nanommo::protocol::LoginReply& listed) {
95 const auto found = std::ranges::find_if(
96 listed.characters(),
97 [](const nanommo::protocol::CharacterListing& character) {
98 return character.world() == kWorld;
99 });
100 return found != listed.characters().end() ? found->id() : 0u;
101 };
102 uint32_t character = mine(*reply);
103 if (character == 0) {
104 nanommo::protocol::LoginRequest create = next;
105 create.set_create_character(true);
106 create.set_world(kWorld);
107 create.set_name(name);
108 reply = Ask(host, tls, create);
109 if (!reply.ok()) {
110 return reply.status();
111 }
112 character = mine(*reply);
113 }
114 next.set_enter(true);
115 next.set_character(character);
116 reply = Ask(host, tls, next);
117 if (!reply.ok()) {
118 return reply.status();
119 }
120 return reply->token();
121}
122
123// What came of a login, for the metrics.
124const char* Outcome(const absl::Status& status) {
125 if (status.ok()) {
126 return "ok";
127 }
128 if (absl::IsPermissionDenied(status)) {
129 return "refused";
130 }
131 return absl::IsDeadlineExceeded(status) ? "timeout" : "failed";
132}
133
134class Swarm {
135 public:
136 Swarm(asio::io_context& io, asio::ssl::context& tls, std::string login,
137 std::string host, asio::ip::tcp::resolver::results_type server,
138 int count, std::chrono::milliseconds ramp, int first, bool udp,
139 bool war, nanommo::BotMetrics& metrics, const nanommo::Content& content)
140 : io_(io),
141 tls_(tls),
142 login_(std::move(login)),
143 host_(std::move(host)),
144 server_(std::move(server)),
145 count_(count),
146 first_(first),
147 udp_(udp),
148 war_(war),
149 gap_(count > 0 ? ramp / count : ramp),
150 metrics_(metrics),
151 content_(content),
152 timer_(io),
153 report_(io),
154 frame_(io),
155 random_(static_cast<uint32_t>(first)) {
156 Add();
157 Report();
158 frame_.expires_after(kFrame);
159 frame_.async_wait([this](std::error_code) { Look(); });
160 }
161
162 private:
163 // At war, the bots with odd numbers are Red, and the even ones Blue, and the
164 // first of each founds and leads it, and asks the rest of its side in.
165 std::optional<nanommo::Side> SideOf(int number) const {
166 if (!war_) {
167 return std::nullopt;
168 }
169 const bool red = number % 2 == 1;
170 nanommo::Side side{.guild = red ? "Red" : "Blue",
171 .enemy = red ? "Blue" : "Red"};
172 // The side has every other bot, the first's half rounding up. Each waits
173 // in lines of five, a metre and a half apart, eight metres either side of
174 // where new players come in, until they're all in the guild.
175 const int place = (number - first_) / 2;
176 const int line = place / 5;
177 const int in_line = place % 5;
178 side.size = (count_ + (place * 2 == number - first_ ? 1 : 0)) / 2;
179 side.camp_x =
180 (red ? -1.0f : 1.0f) * (kCamp + static_cast<float>(line) * kSpacing);
181 side.camp_z = (static_cast<float>(in_line) - 2.0f) * kSpacing;
182 if (number - first_ < 2) {
183 side.leads = true;
184 for (int other = number + 2; other < first_ + count_; other += 2) {
185 side.recruits.push_back("bot" + std::to_string(other));
186 }
187 }
188 return side;
189 }
190
191 void Add() {
192 if (static_cast<int>(bots_.size()) >= count_) {
193 return;
194 }
195 const int number = first_ + static_cast<int>(bots_.size());
196 auto bot =
197 std::make_unique<nanommo::Bot>(io_, tls_, static_cast<uint32_t>(number),
198 udp_, content_, SideOf(number));
199 const auto start = std::chrono::steady_clock::now();
200 const absl::StatusOr<std::string> token = LogIn(login_, tls_, number);
201 const auto now = std::chrono::steady_clock::now();
202 metrics_.ObserveLogin(Outcome(token.status()), now - start);
203 if (token.ok()) {
204 bot->Start(server_, *token);
205 retries_.push_back({.next = now + kGrace});
206 } else {
207 std::cerr << "nanommo bot: bot" << number
208 << " couldn't log in: " << token.status() << "\n";
209 retries_.push_back(
210 {.next = now + nanommo::Backoff(0, random_), .failed = 1});
211 }
212 bots_.push_back(std::move(bot));
213 timer_.expires_after(gap_);
214 timer_.async_wait([this](std::error_code error) {
215 if (!error) {
216 Add();
217 }
218 });
219 }
220
221 // A bot whose world hands its players over goes to the world's next
222 // instance, as a client does, with the move's token. Bots play against a
223 // single machine, so the bot keeps its host, and takes the move's port.
224 void Follow() {
225 int moved = 0;
226 for (std::size_t i = 0; i < bots_.size(); ++i) {
227 const std::optional<nanommo::protocol::Move>& move = bots_[i]->move();
228 if (!move) {
229 continue;
230 }
231 std::error_code error;
232 // IPv4, which the servers listen on, as LogIn looks up.
233 const asio::ip::tcp::resolver::results_type next =
234 asio::ip::tcp::resolver(io_).resolve(
235 asio::ip::tcp::v4(), host_, std::to_string(move->port()), error);
236 if (error) {
237 std::cerr << "nanommo bot: couldn't find " << host_ << ": "
238 << error.message() << "\n";
239 continue;
240 }
241 const std::string token = move->token();
242 const int number = first_ + static_cast<int>(i);
243 // The bot before stays until we stop, as its handlers may be waiting
244 // on its sockets.
245 bots_[i]->Leave();
246 left_.push_back(std::move(bots_[i]));
247 bots_[i] = std::make_unique<nanommo::Bot>(io_, tls_,
248 static_cast<uint32_t>(number),
249 udp_, content_, SideOf(number));
250 bots_[i]->Start(next, token);
251 ++moved;
252 }
253 if (moved > 0) {
254 std::cout << "nanommo bot: " << moved << " bots moved" << std::endl;
255 }
256 }
257
258 // A bot that's lost its world, say as a world that stalled past its leases
259 // dropped it, or that couldn't log in, logs in again, as a player would,
260 // after a wait that doubles with each try that fails, and a few a second at
261 // most.
262 void Rejoin() {
263 const auto now = std::chrono::steady_clock::now();
264 int tried = 0;
265 int rejoined = 0;
266 for (std::size_t i = 0; i < bots_.size() && tried < kRejoinsPerSecond;
267 ++i) {
268 Retry& retry = retries_[i];
269 if (bots_[i]->connected()) {
270 retry = {.next = now + kGrace};
271 continue;
272 }
273 if (bots_[i]->move() || now < retry.next) {
274 continue;
275 }
276 ++tried;
277 const int number = first_ + static_cast<int>(i);
278 const auto start = std::chrono::steady_clock::now();
279 const absl::StatusOr<std::string> token = LogIn(login_, tls_, number);
280 metrics_.ObserveLogin(Outcome(token.status()),
281 std::chrono::steady_clock::now() - start);
282 if (!token.ok()) {
283 std::cerr << "nanommo bot: bot" << number
284 << " couldn't log in again: " << token.status() << "\n";
285 retry.next = now + nanommo::Backoff(retry.failed++, random_);
286 continue;
287 }
288 // The bot before stays until we stop, as its handlers may be waiting
289 // on its sockets.
290 bots_[i]->Leave();
291 left_.push_back(std::move(bots_[i]));
292 bots_[i] = std::make_unique<nanommo::Bot>(io_, tls_,
293 static_cast<uint32_t>(number),
294 udp_, content_, SideOf(number));
295 bots_[i]->Start(server_, *token);
296 retry.next = now + kGrace;
297 ++rejoined;
298 }
299 if (rejoined > 0) {
300 std::cout << "nanommo bot: " << rejoined << " bots logged in again"
301 << std::endl;
302 }
303 }
304
305 void Report() {
306 int connected = 0;
307 for (const auto& bot : bots_) {
308 connected += bot->connected() ? 1 : 0;
309 }
310 metrics_.SetConnected(connected);
311 // After the count, as a bot that moves takes a moment to connect again.
312 Follow();
313 Rejoin();
314 if (connected != reported_) {
315 std::cout << "nanommo bot: " << connected << " of " << count_
316 << " bots connected" << std::endl;
317 reported_ = connected;
318 }
319 report_.expires_after(std::chrono::seconds(1));
320 report_.async_wait([this](std::error_code error) {
321 if (!error) {
322 Report();
323 }
324 });
325 }
326
327 void Look() {
328 const int64_t now = nanommo::NowMicros();
329 for (const auto& bot : bots_) {
330 if (!bot->connected()) {
331 continue;
332 }
333 for (const int64_t sent : bot->newest()) {
334 if (sent > 0) {
335 metrics_.ObserveAge(std::chrono::microseconds(now - sent));
336 }
337 }
338 }
339 frame_.expires_at(frame_.expiry() + kFrame);
340 frame_.async_wait([this](std::error_code error) {
341 if (!error) {
342 Look();
343 }
344 });
345 }
346
347 asio::io_context& io_;
348 asio::ssl::context& tls_;
349 std::string login_;
350 std::string host_;
351 asio::ip::tcp::resolver::results_type server_;
352 int count_;
353 int first_;
354 bool udp_;
355 bool war_;
356 std::chrono::milliseconds gap_;
357 nanommo::BotMetrics& metrics_;
358 const nanommo::Content& content_;
359 asio::steady_timer timer_;
360 asio::steady_timer report_;
361 asio::steady_timer frame_;
362 std::vector<std::unique_ptr<nanommo::Bot>> bots_;
363 std::vector<std::unique_ptr<nanommo::Bot>> left_;
364 // When each bot, by its place in bots_, may log in again, and how many of
365 // its tries have failed in a row.
366 struct Retry {
367 std::chrono::steady_clock::time_point next;
368 int failed = 0;
369 };
370 std::vector<Retry> retries_;
371 std::mt19937 random_;
372 int reported_ = 0;
373};
374
375} // namespace
376
377int main(int argc, char* argv[]) {
378 const std::string login = argc > 1 ? argv[1] : "localhost";
379 const std::string host = argc > 2 ? argv[2] : "localhost";
380 int count = 100;
381 int ramp_seconds = 10;
382 int first = 1;
383 if ((argc > 3 && !absl::SimpleAtoi(argv[3], &count)) ||
384 (argc > 4 && !absl::SimpleAtoi(argv[4], &ramp_seconds)) ||
385 (argc > 5 && !absl::SimpleAtoi(argv[5], &first))) {
386 std::cerr << "nanommo bot: the number of bots, the ramp in seconds and the "
387 "first bot's number should be numbers\n";
388 return 1;
389 }
390 const auto ramp = std::chrono::seconds(ramp_seconds);
391 const std::string transport = argc > 6 ? argv[6] : "udp";
392 // war sends the bots to war, in two guilds.
393 const bool war = argc > 7 && std::string_view(argv[7]) == "war";
394
395 absl::StatusOr<asio::ssl::context> tls =
396 nanommo::ClientTls(nanommo::FileSetting("NANOMMO_TLS_CA", "tls/ca.crt"));
397 if (!tls.ok()) {
398 std::cerr << "nanommo bot: " << tls.status() << "\n";
399 return 1;
400 }
401
402 const absl::StatusOr<nanommo::Content> content =
403 nanommo::ReadContent(nanommo::FileSetting("NANOMMO_CONTENT", "content"));
404 if (!content.ok()) {
405 std::cerr << "nanommo bot: " << content.status() << "\n";
406 return 1;
407 }
408
409 nanommo::BotMetrics metrics(transport);
410 prometheus::Exposer exposer("0.0.0.0:" + std::to_string(kMetricsPort));
411 exposer.RegisterCollectable(metrics.registry());
412
413 asio::io_context io;
414 asio::ip::tcp::resolver resolver(io);
415 std::error_code error;
416 // IPv4, which the servers listen on, as LogIn looks up.
417 const asio::ip::tcp::resolver::results_type server = resolver.resolve(
418 asio::ip::tcp::v4(), host, std::to_string(kGamePort), error);
419 if (error) {
420 std::cerr << "nanommo bot: couldn't find " << host << ": "
421 << error.message() << "\n";
422 return 1;
423 }
424 std::cout << "nanommo bot: starting " << count << " bots against " << host
425 << ", logging in on " << login << ", over " << ramp.count()
426 << " s, from bot" << first << ", worlds over " << transport
427 << (war ? ", at war" : "") << std::endl;
428 Swarm swarm(io, *tls, login, host, server, count, ramp, first,
429 transport == "udp", war, metrics, *content);
430
431 asio::signal_set signals(io, SIGINT, SIGTERM);
432 signals.async_wait([&io](std::error_code, int) { io.stop(); });
433 io.run();
434 std::cout << "nanommo bot: stopped" << std::endl;
435 return 0;
436}
const std::shared_ptr< prometheus::Registry > & registry() const
Definition bot_metrics.h:30
int main()
Definition login_main.cc:28
std::chrono::milliseconds Backoff(int failed, std::mt19937 &random)
Definition backoff.cc:9
const char * Outcome(const absl::StatusOr< protocol::LoginReply > &handled)
absl::StatusOr< protocol::LoginReply > LogIn(const std::string &host, uint16_t port, asio::ssl::context &tls, const protocol::LoginRequest &request, std::chrono::milliseconds deadline)
std::string FileSetting(const char *name, const std::string &path)
Definition settings.cc:22
absl::StatusOr< asio::ssl::context > ClientTls(const std::string &authority)
Definition tls.cc:41
int64_t NowMicros()
Definition clock.h:11
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
int size
How many bots are on the side, its leader with them.
Definition war.h:26
float camp_x
Definition war.h:29
std::vector< std::string > recruits
Definition war.h:21
bool leads
Definition war.h:24
float camp_z
Definition war.h:30