nanoMMO 0.97.8
Building an MMO: The Engineering Series
Loading...
Searching...
No Matches
tracing.cc
Go to the documentation of this file.
1#include "server/tracing.h"
2
3#include <httplib.h>
4
5#include <algorithm>
6#include <atomic>
7#include <chrono>
8#include <condition_variable>
9#include <cstddef>
10#include <cstdint>
11#include <iostream>
12#include <memory>
13#include <mutex>
14#include <span>
15#include <string>
16#include <string_view>
17#include <thread>
18#include <utility>
19#include <variant>
20#include <vector>
21
22#include "absl/random/random.h"
23#include "absl/strings/numbers.h"
24#include "absl/strings/str_cat.h"
25#include "absl/strings/str_split.h"
26#include "absl/time/clock.h"
27#include "absl/time/time.h"
28#include "nlohmann/json.hpp"
29#include "prometheus/counter.h"
30
31namespace nanommo {
32
33struct Span::Data {
34 std::string name;
37 uint64_t parent = 0;
38 int64_t start = 0;
39 int64_t end = 0;
40 std::vector<std::pair<std::string, std::variant<std::string, int64_t>>>
42 bool failed = false;
43 std::string error;
44 std::vector<SpanContext> links;
45};
46
47namespace {
48
49// A batch goes once a second, or as soon as there are this many.
50constexpr std::size_t kBatch = 512;
51constexpr std::chrono::seconds kSendEvery{1};
52// What's left as tracing stops goes within this long, or is dropped, so that a
53// collector that's slow, or gone, can't hold up a server that's stopping.
54constexpr std::chrono::seconds kStopWithin{2};
55
56std::string Hex(uint64_t id) {
57 return absl::StrCat(absl::Hex(id, absl::kZeroPad16));
58}
59
60// An id nobody else has made: random, and never zero, which is no id.
61uint64_t RandomId() {
62 // Seeded from the system once per thread, and quick after that.
63 thread_local absl::BitGen random;
64 uint64_t id = 0;
65 while (id == 0) {
66 id = absl::Uniform<uint64_t>(random);
67 }
68 return id;
69}
70
71bool IsLowerHex(std::string_view text) {
72 return std::ranges::all_of(text, [](char c) {
73 return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
74 });
75}
76
77nlohmann::json Attribute(std::string_view key,
78 const std::variant<std::string, int64_t>& value) {
79 nlohmann::json written;
80 if (const auto* text = std::get_if<std::string>(&value)) {
81 written["stringValue"] = *text;
82 } else if (const auto* number = std::get_if<int64_t>(&value)) {
83 // OTLP's JSON writes a 64-bit number as a string.
84 written["intValue"] = absl::StrCat(*number);
85 }
86 return {{"key", key}, {"value", written}};
87}
88
89// The spans as OTLP's JSON: a resource, the service, with a scope, ours, with
90// the spans. Ids go in hex, kinds as numbers, and times as strings of
91// nanoseconds since 1970.
92std::string Json(const std::string& service,
93 std::span<const Span::Data> spans) {
94 nlohmann::json written = nlohmann::json::array();
95 for (const Span::Data& span : spans) {
96 nlohmann::json attributes = nlohmann::json::array();
97 for (const auto& [key, value] : span.attributes) {
98 attributes.push_back(Attribute(key, value));
99 }
100 nlohmann::json json = {
101 {"traceId", span.context.trace_id()},
102 {"spanId", Hex(span.context.span)},
103 {"name", span.name},
104 {"kind", static_cast<int>(span.kind)},
105 {"startTimeUnixNano", absl::StrCat(span.start)},
106 {"endTimeUnixNano", absl::StrCat(span.end)},
107 {"attributes", std::move(attributes)},
108 };
109 if (span.parent != 0) {
110 json["parentSpanId"] = Hex(span.parent);
111 }
112 // Code 2 is an error.
113 if (span.failed) {
114 json["status"] = {{"code", 2}, {"message", span.error}};
115 }
116 for (const SpanContext& link : span.links) {
117 json["links"].push_back(
118 {{"traceId", link.trace_id()}, {"spanId", Hex(link.span)}});
119 }
120 written.push_back(std::move(json));
121 }
122 nlohmann::json resource;
123 resource["attributes"] = nlohmann::json::array(
124 {Attribute("service.name", std::variant<std::string, int64_t>(service))});
125 nlohmann::json scope;
126 scope["scope"] = {{"name", "nanommo"}};
127 scope["spans"] = std::move(written);
128 nlohmann::json batch;
129 batch["resource"] = std::move(resource);
130 batch["scopeSpans"] = nlohmann::json::array({std::move(scope)});
131 nlohmann::json request;
132 request["resourceSpans"] = nlohmann::json::array({std::move(batch)});
133 // dump would throw at bytes that aren't UTF-8, and replaces them instead.
134 return request.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace);
135}
136
137// Takes the spans as they end, from any thread, and sends them from its own,
138// so a span ending never waits on the collector.
139class Exporter {
140 public:
141 Exporter(std::string service, SendSpans send, prometheus::Counter* dropped)
142 : service_(std::move(service)),
143 send_(std::move(send)),
144 dropped_(dropped),
145 thread_([this] { Run(); }) {}
146
147 ~Exporter() {
148 {
149 const std::lock_guard lock(mutex_);
150 stopping_ = true;
151 give_up_at_ = std::chrono::steady_clock::now() + kStopWithin;
152 }
153 wake_.notify_one();
154 thread_.join();
155 }
156
157 Exporter(const Exporter&) = delete;
158 Exporter& operator=(const Exporter&) = delete;
159
160 void Take(Span::Data span) {
161 std::unique_lock lock(mutex_);
162 // The span may be the tick thread's, which mustn't wait, so when the
163 // queue's full, it's dropped.
164 if (waiting_.size() >= kMostWaitingSpans) {
165 lock.unlock();
166 Drop(1);
167 return;
168 }
169 waiting_.push_back(std::move(span));
170 const bool batch = waiting_.size() >= kBatch;
171 lock.unlock();
172 if (batch) {
173 wake_.notify_one();
174 }
175 }
176
177 private:
178 void Run() {
179 std::unique_lock lock(mutex_);
180 while (!stopping_ || !waiting_.empty()) {
181 wake_.wait_for(lock, kSendEvery,
182 [this] { return stopping_ || waiting_.size() >= kBatch; });
183 std::vector<Span::Data> spans;
184 spans.swap(waiting_);
185 const auto give_up_at = give_up_at_;
186 lock.unlock();
187 for (std::size_t first = 0; first < spans.size(); first += kBatch) {
188 if (std::chrono::steady_clock::now() > give_up_at) {
189 Drop(spans.size() - first);
190 break;
191 }
192 const std::span<const Span::Data> batch =
193 std::span<const Span::Data>(spans).subspan(
194 first, std::min(kBatch, spans.size() - first));
195 Report(send_(Json(service_, batch)), batch.size());
196 }
197 lock.lock();
198 }
199 }
200
201 // A batch that didn't go is dropped, as the spans after it keep coming.
202 void Report(const absl::Status& sent, std::size_t spans) {
203 if (!sent.ok()) {
204 Drop(spans);
205 }
206 // Once when it changes, not with each batch.
207 const std::string news = sent.ok() ? "" : sent.ToString();
208 if (news != said_) {
209 said_ = news;
210 std::cerr << "nanommo tracing: "
211 << (sent.ok() ? "sending spans again" : news) << "\n";
212 }
213 }
214
215 void Drop(std::size_t spans) {
216 if (dropped_ != nullptr) {
217 dropped_->Increment(static_cast<double>(spans));
218 }
219 }
220
221 const std::string service_;
222 const SendSpans send_;
223 prometheus::Counter* const dropped_;
224 std::string said_;
225 std::mutex mutex_;
226 std::condition_variable wake_;
227 std::vector<Span::Data> waiting_;
228 bool stopping_ = false;
229 std::chrono::steady_clock::time_point give_up_at_ =
230 std::chrono::steady_clock::time_point::max();
231 // Last, so the rest is ready before it runs.
232 std::thread thread_;
233};
234
235// The exporter while tracing is on, and nullptr while it's off.
236std::atomic<Exporter*> exporter{nullptr};
237
238// The span that's open on this thread, which the next one started on it is
239// part of.
240thread_local SpanContext current;
241
242Span Start(std::string_view name, SpanKind kind, const SpanContext& parent,
243 absl::Time start) {
244 if (exporter.load() == nullptr) {
245 return Span();
246 }
247 auto data = std::make_unique<Span::Data>();
248 data->name = name;
249 data->kind = kind;
250 data->start = absl::ToUnixNanos(start);
251 // A child is in its parent's trace, and the first span of a trace makes it.
252 if (parent.valid()) {
253 data->context = parent;
254 data->parent = parent.span;
255 } else {
256 data->context.trace_high = RandomId();
257 data->context.trace_low = RandomId();
258 }
259 data->context.span = RandomId();
260 return Span(std::move(data));
261}
262
263} // namespace
264
265std::string SpanContext::trace_id() const {
266 return absl::StrCat(Hex(trace_high), Hex(trace_low));
267}
268
269std::string Traceparent(const SpanContext& context) {
270 // The flags at the end, 01, say the trace is being kept.
271 return absl::StrCat("00-", context.trace_id(), "-", Hex(context.span), "-01");
272}
273
274absl::StatusOr<SpanContext> ParseTraceparent(std::string_view traceparent) {
275 // Version 00, the only one there is, has four parts, in lowercase hex.
276 const std::vector<std::string_view> parts = absl::StrSplit(traceparent, '-');
277 if (parts.size() != 4 || parts[0] != "00" || parts[1].size() != 32 ||
278 parts[2].size() != 16 || parts[3].size() != 2 ||
279 !std::ranges::all_of(parts, IsLowerHex)) {
280 return absl::InvalidArgumentError(
281 absl::StrCat("not a traceparent: ", traceparent));
282 }
283 SpanContext context;
284 if (!absl::SimpleHexAtoi(parts[1].substr(0, 16), &context.trace_high) ||
285 !absl::SimpleHexAtoi(parts[1].substr(16), &context.trace_low) ||
286 !absl::SimpleHexAtoi(parts[2], &context.span)) {
287 return absl::InvalidArgumentError(
288 absl::StrCat("not a traceparent: ", traceparent));
289 }
290 // All zeros is no trace, and no span.
291 if ((context.trace_high == 0 && context.trace_low == 0) ||
292 context.span == 0) {
293 return absl::InvalidArgumentError(
294 absl::StrCat("a traceparent with no trace: ", traceparent));
295 }
296 return context;
297}
298
299Span::Span() = default;
300
301Span::Span(std::unique_ptr<Data> data) : data_(std::move(data)) {
302 previous_ = current;
303 current = data_->context;
304}
305
306Span::Span(Span&& other) noexcept = default;
307
309
311 return data_ != nullptr ? data_->context : SpanContext();
312}
313
314void Span::SetAttribute(std::string_view key, std::string_view value) {
315 if (data_ != nullptr) {
316 data_->attributes.emplace_back(key, std::string(value));
317 }
318}
319
320void Span::SetAttribute(std::string_view key, int64_t value) {
321 if (data_ != nullptr) {
322 data_->attributes.emplace_back(key, value);
323 }
324}
325
326void Span::SetError(std::string_view message) {
327 if (data_ != nullptr) {
328 data_->failed = true;
329 data_->error = message;
330 }
331}
332
333void Span::AddLink(const SpanContext& other) {
334 if (data_ != nullptr && other.valid()) {
335 data_->links.push_back(other);
336 }
337}
338
339void Span::End() {
340 if (data_ == nullptr) {
341 return;
342 }
343 data_->end = absl::ToUnixNanos(absl::Now());
344 current = previous_;
345 if (Exporter* const sending = exporter.load(); sending != nullptr) {
346 sending->Take(std::move(*data_));
347 }
348 data_.reset();
349}
350
351SendSpans PostTo(const std::string& endpoint) {
352 return [endpoint](const std::string& json) -> absl::Status {
353 httplib::Client http(endpoint);
354 http.set_connection_timeout(1);
355 http.set_read_timeout(2);
356 const httplib::Result result =
357 http.Post("/v1/traces", json, "application/json");
358 if (!result) {
359 return absl::UnavailableError(
360 absl::StrCat("couldn't reach ", endpoint, ": ",
361 httplib::to_string(result.error())));
362 }
363 if (result->status != 200) {
364 return absl::InternalError(absl::StrCat(
365 endpoint, " answered ", result->status, ": ", result->body));
366 }
367 return absl::OkStatus();
368 };
369}
370
371void StartTracing(std::string service, SendSpans send,
372 prometheus::Registry* registry) {
373 prometheus::Counter* dropped = nullptr;
374 if (registry != nullptr) {
375 dropped = &prometheus::BuildCounter()
376 .Name("nanommo_spans_dropped_total")
377 .Help(
378 "Spans that ended while the queue was full, or "
379 "that the collector didn't take")
380 .Register(*registry)
381 .Add({});
382 }
383 delete exporter.exchange(
384 new Exporter(std::move(service), std::move(send), dropped));
385}
386
387void StopTracing() { delete exporter.exchange(nullptr); }
388
389Span StartSpan(std::string_view name, SpanKind kind) {
390 return Start(name, kind, current, absl::Now());
391}
392
393Span StartSpan(std::string_view name, SpanKind kind, const SpanContext& parent,
394 absl::Time start) {
395 return Start(name, kind, parent, start);
396}
397
398std::string TraceField() {
399 return current.valid() ? absl::StrCat(" trace_id=", current.trace_id()) : "";
400}
401
402bool InTrace() { return current.valid(); }
403
404Span StartChildSpan(std::string_view name, SpanKind kind) {
405 if (!InTrace()) {
406 return Span();
407 }
408 return Start(name, kind, current, absl::Now());
409}
410
411} // namespace nanommo
Span()
A span that records nothing.
void SetAttribute(std::string_view key, std::string_view value)
Definition tracing.cc:314
void SetError(std::string_view message)
Marks it as failed, and why.
Definition tracing.cc:326
void AddLink(const SpanContext &other)
Definition tracing.cc:333
SpanContext context() const
No trace and no span when it isn't recording.
Definition tracing.cc:310
Definition chat.cc:9
std::string Traceparent(const SpanContext &context)
Definition tracing.cc:269
Span StartSpan(std::string_view name, SpanKind kind)
Definition tracing.cc:389
void StopTracing()
Definition tracing.cc:387
bool InTrace()
Definition tracing.cc:402
std::function< absl::Status(const std::string &json)> SendSpans
Sends a batch of spans, written as OTLP's JSON, and says whether it went.
Definition tracing.h:93
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< SpanContext > ParseTraceparent(std::string_view traceparent)
Definition tracing.cc:274
std::string TraceField()
Definition tracing.cc:398
Span StartChildSpan(std::string_view name, SpanKind kind)
Definition tracing.cc:404
constexpr std::size_t kMostWaitingSpans
Definition tracing.h:101
uint64_t trace_low
Definition tracing.h:23
bool valid() const
Definition tracing.h:26
uint64_t trace_high
Definition tracing.h:22
std::string trace_id() const
The trace's id, as 32 hex digits, as Tempo shows it.
Definition tracing.cc:265
std::vector< SpanContext > links
Definition tracing.cc:44
std::vector< std::pair< std::string, std::variant< std::string, int64_t > > > attributes
Definition tracing.cc:41
SpanContext context
Definition tracing.cc:36
std::string name
Definition tracing.cc:34
std::string error
Definition tracing.cc:43