Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion test/test_trace_client.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -346,7 +346,7 @@ static void aLoggerThatThrowsDoesNotStopTheSendingThread() {
static void aLoggerMayItselfReport() {
// The logger runs on the sending thread; a report from inside it is
// queued and sent like any other, not a deadlock. The test waits for that
// report() to return before close(): one racing close() is issue #14.
// report() to return before close(): one racing close() is the next test.
StubServer server;
server.status = 500;
trace_client::TraceClient *self = NULL;
Expand All @@ -372,6 +372,37 @@ static void aLoggerMayItselfReport() {
CHECK(got[1].body.find("\"name\":\"logged\"") != std::string::npos);
}

static void aLoggerMayReportWhileCloseIsRunning() {
// close() starts while the logger is running and the logger then calls
// report(): nothing orders the two threads, so this is the race of issue
// #14, which ThreadSanitizer reports unless report() and close() share a
// lock. Either outcome for "logged" is allowed; a crash or a hang is not.
StubServer server;
server.status = 500;
trace_client::TraceClient *self = NULL;
std::atomic<bool> inLogger(false);
std::atomic<bool> returned(false);
trace_client::Logger reporting = [&self, &inLogger, &returned](const std::string &) {
if (inLogger.exchange(true)) return;
std::this_thread::sleep_for(std::chrono::milliseconds(200));
self->report("logged");
returned = true;
};
trace_client::TraceClient client(server.baseUrl(), "MyGame", "1.2.3", "k", true, reporting);
self = &client;
client.report("startup");
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
while (!inLogger && secondsSince(start) < 10) std::this_thread::sleep_for(std::chrono::milliseconds(1));
CHECK(inLogger);
client.close();
CHECK(returned);
CHECK(!client.isEnabled());
std::vector<Request> got = server.received();
CHECK(!got.empty());
if (got.empty()) return;
CHECK(got[0].body.find("\"name\":\"startup\"") != std::string::npos);
}

static void theLoggerIsNeverCalledOnceCloseReturns() {
StubServer server;
server.hold(); // the request in flight never answers, so close() gives up on it
Expand Down Expand Up @@ -1255,6 +1286,7 @@ int main() {
{"rejectedKeyIsLoggedNotThrown", rejectedKeyIsLoggedNotThrown},
{"aLoggerThatThrowsDoesNotStopTheSendingThread", aLoggerThatThrowsDoesNotStopTheSendingThread},
{"aLoggerMayItselfReport", aLoggerMayItselfReport},
{"aLoggerMayReportWhileCloseIsRunning", aLoggerMayReportWhileCloseIsRunning},
{"theLoggerIsNeverCalledOnceCloseReturns", theLoggerIsNeverCalledOnceCloseReturns},
{"missingCurlIsAnUnreachableServer", missingCurlIsAnUnreachableServer},
{"disabledClientSendsNothing", disabledClientSendsNothing},
Expand Down
38 changes: 28 additions & 10 deletions trace_client.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -1006,7 +1006,7 @@ class TraceClient {
~TraceClient() { close(); }

/** Whether report() will actually send anything. False after close(). */
bool isEnabled() const { return static_cast<bool>(shared_); }
bool isEnabled() const { return static_cast<bool>(current()); }

/**
* Why this client reports nothing: empty when it reports, otherwise one
Expand Down Expand Up @@ -1035,9 +1035,14 @@ class TraceClient {
* then is abandoned. Safe to call more than once, and on a disabled client.
*/
void close(double timeoutSeconds = TIMEOUT_SECONDS) {
if (!shared_) return;
std::shared_ptr<detail::Shared> shared;
shared.swap(shared_);
try {
std::lock_guard<std::mutex> lock(sharedMutex_);
shared.swap(shared_);
} catch (...) {
return;
}
if (!shared) return;
try {
std::unique_lock<std::mutex> lock(shared->mutex);
shared->closing = true;
Expand Down Expand Up @@ -1135,26 +1140,39 @@ class TraceClient {
#endif
}

// A copy of shared_, taken under its lock: the logger runs on the sending
// thread and may call report() while the program's thread is in close().
std::shared_ptr<detail::Shared> current() const {
try {
std::lock_guard<std::mutex> lock(sharedMutex_);
return shared_;
} catch (...) {
return std::shared_ptr<detail::Shared>();
}
}

void enqueue(const std::string &name, bool hasValue, double value, const Tags &tags) {
if (!shared_ || detail::isBlank(name)) return;
std::shared_ptr<detail::Shared> shared = current();
if (!shared || detail::isBlank(name)) return;
try {
std::string body = detail::json(shared_->application, name, hasValue, value,
std::string body = detail::json(shared->application, name, hasValue, value,
detail::withInstall(detail::withVersion(tags, version_), installId_));
bool full = false;
{
std::lock_guard<std::mutex> lock(shared_->mutex);
full = shared_->queue.size() >= QUEUE_CAPACITY;
std::lock_guard<std::mutex> lock(shared->mutex);
full = shared->queue.size() >= QUEUE_CAPACITY;
if (!full) {
shared_->queue.push_back(body);
shared_->changed.notify_all();
shared->queue.push_back(body);
shared->changed.notify_all();
}
}
if (full) shared_->log("queue full, dropped " + name);
if (full) shared->log("queue full, dropped " + name);
} catch (...) {
// a report must never be the reason a program stops
}
}

mutable std::mutex sharedMutex_; // guards shared_ alone
std::shared_ptr<detail::Shared> shared_;
std::thread thread_;
std::string version_;
Expand Down
Loading