blob: d438c688d7d80dd22a3c92d807746ee36f650d95 [file]
// Copyright 2021 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/developer/forensics/feedback/namespace_init.h"
#include <lib/syslog/cpp/macros.h>
#include <gmock/gmock.h>
#include <gtest/gtest.h>
#include "src/developer/forensics/feedback_data/system_log_recorder/encoding/production_encoding.h"
#include "src/developer/forensics/testing/log_message.h"
#include "src/developer/forensics/testing/stubs/cobalt_logger_factory.h"
#include "src/developer/forensics/testing/unit_test_fixture.h"
#include "src/developer/forensics/utils/log_format.h"
#include "src/lib/files/directory.h"
#include "src/lib/files/file.h"
#include "src/lib/files/path.h"
#include "src/lib/files/scoped_temp_dir.h"
#include "src/lib/timekeeper/test_clock.h"
namespace forensics::feedback {
namespace {
using testing::BuildLogMessage;
using ::testing::IsEmpty;
using ::testing::TestParamInfo;
using ::testing::UnorderedElementsAre;
using ::testing::UnorderedElementsAreArray;
using ::testing::ValuesIn;
using ::testing::WithParamInterface;
MATCHER_P2(MatchesCobaltEvent, expected_type, expected_metric_id, "") {
return arg.type == expected_type && arg.metric_id == expected_metric_id;
}
std::string MakeFilepath(const std::string& dir, const size_t file_num) {
return files::JoinPath(dir, std::to_string(file_num));
}
std::string MakeFilepath(const std::string& dir, const std::string& file) {
return files::JoinPath(dir, file);
}
const std::vector<std::string> CurrentLogFilePaths(const std::string& dir) {
return {MakeFilepath(dir, 0), MakeFilepath(dir, 1), MakeFilepath(dir, 2), MakeFilepath(dir, 3),
MakeFilepath(dir, 4), MakeFilepath(dir, 5), MakeFilepath(dir, 6), MakeFilepath(dir, 7)};
}
class NamespaceInitTest : public UnitTestFixture {
protected:
std::string RootdDir() { return temp_dir_.path(); }
void WriteFile(const std::string& path, const std::string& content) {
FX_CHECK(files::WriteFile(path, content)) << "Failed to write to " << path;
}
void DeleteFile(const std::string& path) {
FX_CHECK(files::DeletePath(path, /*recursive=*/true)) << "Failed to delete to " << path;
}
std::string ReadFile(const std::string& path) {
std::string content;
FX_CHECK(files::ReadFileToString(path, &content)) << "Failed to read from " << path;
return content;
}
files::ScopedTempDir temp_dir_;
};
TEST_F(NamespaceInitTest, TestAndSetNotAFdr) {
std::string path = MakeFilepath(RootdDir(), "not_a_fdr.txt");
EXPECT_FALSE(TestAndSetNotAFdr(path));
EXPECT_TRUE(TestAndSetNotAFdr(path));
EXPECT_TRUE(TestAndSetNotAFdr(path));
path = "/bad_path/not_a_fdr.txt";
EXPECT_FALSE(TestAndSetNotAFdr(path));
EXPECT_FALSE(TestAndSetNotAFdr(path));
EXPECT_FALSE(TestAndSetNotAFdr(path));
}
TEST_F(NamespaceInitTest, MoveFile) {
const std::string to = MakeFilepath(RootdDir(), "to.txt");
const std::string from = MakeFilepath(RootdDir(), "from.txt");
// |from| doesn't exist.
MoveFile(from, to);
EXPECT_FALSE(files::IsFile(to));
// |to| can't be written to.
WriteFile(from, "reboot_reason");
MoveFile(from, "/bad_path/to.txt");
EXPECT_FALSE(files::IsFile("/bad_path/to.txt"));
EXPECT_TRUE(files::IsFile(from));
EXPECT_EQ(ReadFile(from), "reboot_reason");
// |from| works!
WriteFile(from, "reboot_reason");
MoveFile(from, to);
EXPECT_FALSE(files::IsFile(from));
EXPECT_TRUE(files::IsFile(to));
EXPECT_EQ(ReadFile(to), "reboot_reason");
}
TEST_F(NamespaceInitTest, MoveAndRecordBootId) {
const std::string to = MakeFilepath(RootdDir(), "to.txt");
const std::string from = MakeFilepath(RootdDir(), "from.txt");
// |from| doesn't exist.
MoveAndRecordBootId("boot-id-1", to, from);
EXPECT_FALSE(files::IsFile(to));
EXPECT_TRUE(files::IsFile(from));
EXPECT_EQ(ReadFile(from), "boot-id-1");
// |to| can't be written to.
MoveAndRecordBootId("boot-id-2", "/bad-path/to.txt", from);
EXPECT_FALSE(files::IsFile("/bad-path/to.txt"));
EXPECT_TRUE(files::IsFile(from));
EXPECT_EQ(ReadFile(from), "boot-id-2");
// Everything works!
WriteFile(from, "boot-id-3");
MoveAndRecordBootId("boot-id-4", to, from);
EXPECT_TRUE(files::IsFile(to));
EXPECT_EQ(ReadFile(to), "boot-id-3");
EXPECT_TRUE(files::IsFile(from));
EXPECT_EQ(ReadFile(from), "boot-id-4");
}
TEST_F(NamespaceInitTest, BootIdTimelineRecorded) {
const std::string to = MakeFilepath(RootdDir(), "to.txt");
const std::string from = MakeFilepath(RootdDir(), "from.txt");
const std::string timeline = MakeFilepath(RootdDir(), "timeline.txt");
// Initial boot.
MoveAndRecordBootId("boot-id-1", to, from, timeline);
EXPECT_EQ(ReadFile(timeline), "[boot-id-1]");
// Second boot.
MoveAndRecordBootId("boot-id-2", to, from, timeline);
EXPECT_EQ(ReadFile(timeline), "[boot-id-2, boot-id-1]");
}
TEST_F(NamespaceInitTest, BootIdTimelinePruned) {
const std::string to = MakeFilepath(RootdDir(), "to.txt");
const std::string from = MakeFilepath(RootdDir(), "from.txt");
const std::string timeline = MakeFilepath(RootdDir(), "timeline.txt");
for (int i = 1; i <= 11; ++i) {
MoveAndRecordBootId("boot-id-" + std::to_string(i), to, from, timeline);
}
EXPECT_EQ(ReadFile(timeline),
"[boot-id-11, boot-id-10, boot-id-9, boot-id-8, boot-id-7, boot-id-6, "
"boot-id-5, boot-id-4, boot-id-3, boot-id-2]");
}
TEST_F(NamespaceInitTest, MoveAndRecordBuildVersion) {
const std::string to = MakeFilepath(RootdDir(), "to.txt");
const std::string from = MakeFilepath(RootdDir(), "from.txt");
// |from| doesn't exist.
MoveAndRecordBuildVersion("build-version-1", to, from);
EXPECT_FALSE(files::IsFile(to));
EXPECT_TRUE(files::IsFile(from));
EXPECT_EQ(ReadFile(from), "build-version-1");
// |to| can't be written to.
MoveAndRecordBuildVersion("build-version-2", "/bad-path/to.txt", from);
EXPECT_FALSE(files::IsFile("/bad-path/to.txt"));
EXPECT_TRUE(files::IsFile(from));
EXPECT_EQ(ReadFile(from), "build-version-2");
// Everything works!
WriteFile(from, "build-version-3");
MoveAndRecordBuildVersion("build-version-4", to, from);
EXPECT_TRUE(files::IsFile(to));
EXPECT_EQ(ReadFile(to), "build-version-3");
EXPECT_TRUE(files::IsFile(from));
EXPECT_EQ(ReadFile(from), "build-version-4");
}
TEST_F(NamespaceInitTest, CreatePreviousLogsFile) {
timekeeper::TestClock clock;
cobalt::Logger cobalt(dispatcher(), services(), &clock);
SetUpCobaltServer(std::make_unique<stubs::CobaltLoggerFactory>(dispatcher()));
std::string logs_dir;
ASSERT_TRUE(temp_dir_.NewTempDir(&logs_dir));
std::string previous_log_contents = "";
for (const std::string& filepath : CurrentLogFilePaths(logs_dir)) {
feedback_data::system_log_recorder::ProductionEncoder encoder;
const std::string str = Format(BuildLogMessage(FUCHSIA_LOG_INFO, "Log for file: " + filepath));
previous_log_contents = previous_log_contents + str;
WriteFile(filepath, encoder.Encode(str));
}
std::string log_file = MakeFilepath(RootdDir(), "log.system.previous_boot.txt");
EXPECT_EQ(CreatePreviousLogsFile(&cobalt, /*max_decompressed_size=*/StorageSize::Kilobytes(128),
logs_dir, log_file),
// BuildLogMessage()'s timestamp.
zx::time_boot(zx::sec(15604).get()));
RunLoopUntilIdle();
EXPECT_FALSE(files::IsDirectory(logs_dir));
EXPECT_EQ(previous_log_contents, ReadFile(log_file));
// Verify the event type and metric_id.
EXPECT_THAT(
ReceivedCobaltEvents(),
UnorderedElementsAreArray({
MatchesCobaltEvent(cobalt::EventType::kInteger,
cobalt_registry::kPreviousBootLogCompressionRatioMigratedMetricId),
}));
}
TEST_F(NamespaceInitTest, CreatePreviousLogsFileLogsMetricsAtCapacity) {
timekeeper::TestClock clock;
cobalt::Logger cobalt(dispatcher(), services(), &clock);
SetUpCobaltServer(std::make_unique<stubs::CobaltLoggerFactory>(dispatcher()));
std::string logs_dir;
ASSERT_TRUE(temp_dir_.NewTempDir(&logs_dir));
feedback_data::system_log_recorder::ProductionEncoder encoder;
const std::string unencoded =
"[00002.000][07559][07687][] INFO: line 0\n"
"!!! MESSAGE REPEATED 2 MORE TIMES !!!\n"
"[00124.000][07559][07687][] INFO: line 1\n";
// File 0 is missing, so the log buffer is at capacity.
WriteFile(MakeFilepath(logs_dir, 1), encoder.Encode(unencoded));
const std::string log_file = MakeFilepath(RootdDir(), "log.system.previous_boot.txt");
EXPECT_EQ(CreatePreviousLogsFile(&cobalt, /*max_decompressed_size=*/StorageSize::Kilobytes(128),
logs_dir, log_file),
zx::time_boot(zx::sec(124).get()));
RunLoopUntilIdle();
EXPECT_THAT(
ReceivedCobaltEvents(),
UnorderedElementsAre(
MatchesCobaltEvent(cobalt::EventType::kInteger,
cobalt_registry::kPreviousBootLogCompressionRatioMigratedMetricId),
cobalt::Event(cobalt::EventType::kInteger,
cobalt_registry::kPreviousBootLogMessageCountAtCapacityMetricId,
{cobalt_registry::FeedbackMetricDimensionProvider::Feedback}, 4),
cobalt::Event(cobalt::EventType::kInteger,
cobalt_registry::kPreviousBootLogDeduplicatedMessageCountAtCapacityMetricId,
{cobalt_registry::FeedbackMetricDimensionProvider::Feedback}, 2),
cobalt::Event(cobalt::EventType::kInteger,
cobalt_registry::kPreviousBootLogDurationAtCapacityMetricId,
{cobalt_registry::FeedbackMetricDimensionProvider::Feedback}, 2)));
}
TEST_F(NamespaceInitTest, CreatePreviousLogsFileLogsMetricsNotAtCapacity) {
timekeeper::TestClock clock;
cobalt::Logger cobalt(dispatcher(), services(), &clock);
SetUpCobaltServer(std::make_unique<stubs::CobaltLoggerFactory>(dispatcher()));
std::string logs_dir;
ASSERT_TRUE(temp_dir_.NewTempDir(&logs_dir));
feedback_data::system_log_recorder::ProductionEncoder encoder;
const std::string unencoded =
"[00002.000][07559][07687][] INFO: line 0\n"
"[00124.000][07559][07687][] INFO: line 1\n";
WriteFile(MakeFilepath(logs_dir, 0), encoder.Encode(unencoded));
const std::string log_file = MakeFilepath(RootdDir(), "log.system.previous_boot.txt");
EXPECT_EQ(CreatePreviousLogsFile(&cobalt, /*max_decompressed_size=*/StorageSize::Kilobytes(128),
logs_dir, log_file),
zx::time_boot(zx::sec(124).get()));
RunLoopUntilIdle();
EXPECT_THAT(ReceivedCobaltEvents(),
UnorderedElementsAre(MatchesCobaltEvent(
cobalt::EventType::kInteger,
cobalt_registry::kPreviousBootLogCompressionRatioMigratedMetricId)));
}
TEST_F(NamespaceInitTest, CreatePreviousLogsFileNoLogs) {
timekeeper::TestClock clock;
cobalt::Logger cobalt(dispatcher(), services(), &clock);
SetUpCobaltServer(std::make_unique<stubs::CobaltLoggerFactory>(dispatcher()));
const std::string logs_dir = MakeFilepath(RootdDir(), "missing");
const std::string log_file = MakeFilepath(RootdDir(), "log.system.previous_boot.txt");
EXPECT_EQ(CreatePreviousLogsFile(&cobalt, /*max_decompressed_size=*/StorageSize::Kilobytes(128),
logs_dir, log_file),
std::nullopt);
RunLoopUntilIdle();
EXPECT_FALSE(files::IsFile(log_file));
EXPECT_THAT(ReceivedCobaltEvents(), IsEmpty());
}
TEST_F(NamespaceInitTest, CreatePreviousLogsFileWriteFails) {
timekeeper::TestClock clock;
cobalt::Logger cobalt(dispatcher(), services(), &clock);
SetUpCobaltServer(std::make_unique<stubs::CobaltLoggerFactory>(dispatcher()));
std::string logs_dir;
ASSERT_TRUE(temp_dir_.NewTempDir(&logs_dir));
feedback_data::system_log_recorder::ProductionEncoder encoder;
const std::string unencoded =
"[00002.000][07559][07687][] INFO: line 0\n"
"[00124.000][07559][07687][] INFO: line 1\n";
WriteFile(MakeFilepath(logs_dir, 0), encoder.Encode(unencoded));
const std::string log_file = "/bad_path/log.system.previous_boot.txt";
EXPECT_EQ(CreatePreviousLogsFile(&cobalt, /*max_decompressed_size=*/StorageSize::Kilobytes(128),
logs_dir, log_file),
zx::time_boot(zx::sec(124).get()));
RunLoopUntilIdle();
EXPECT_TRUE(files::IsDirectory(logs_dir));
EXPECT_FALSE(files::IsFile(log_file));
EXPECT_THAT(ReceivedCobaltEvents(), IsEmpty());
}
struct LastTimestampDeltaTestParam {
std::string test_name;
std::optional<zx::time_boot> last_log_timestamp;
std::optional<zx::duration> last_boot_uptime;
std::optional<int64_t> expected_delta_ms;
};
class LastTimestampDeltaTest : public NamespaceInitTest,
public WithParamInterface<LastTimestampDeltaTestParam> {};
INSTANTIATE_TEST_SUITE_P(WithVariousTimes, LastTimestampDeltaTest,
ValuesIn(std::vector<LastTimestampDeltaTestParam>({
{
.test_name = "PositiveDelta",
.last_log_timestamp = zx::time_boot(zx::sec(124).get()),
.last_boot_uptime = zx::sec(124) + zx::msec(55),
.expected_delta_ms = 55,
},
{
.test_name = "NegativeDelta",
.last_log_timestamp = zx::time_boot(zx::sec(120).get()),
.last_boot_uptime = zx::sec(100),
.expected_delta_ms = -20000,
},
{
.test_name = "NoLastLogTimestamp",
.last_log_timestamp = std::nullopt,
.last_boot_uptime = zx::sec(100),
.expected_delta_ms = std::nullopt,
},
{
.test_name = "NoLastBootUptime",
.last_log_timestamp = zx::time_boot(zx::sec(120).get()),
.last_boot_uptime = std::nullopt,
.expected_delta_ms = std::nullopt,
},
})),
[](const TestParamInfo<LastTimestampDeltaTestParam>& info) {
return info.param.test_name;
});
TEST_P(LastTimestampDeltaTest, LogsDelta) {
const LastTimestampDeltaTestParam& param = GetParam();
timekeeper::TestClock clock;
cobalt::Logger cobalt(dispatcher(), services(), &clock);
SetUpCobaltServer(std::make_unique<stubs::CobaltLoggerFactory>(dispatcher()));
LogPreviousBootLogLastTimestampDelta(&cobalt, param.last_log_timestamp, param.last_boot_uptime);
RunLoopUntilIdle();
if (param.expected_delta_ms.has_value()) {
EXPECT_THAT(ReceivedCobaltEvents(),
UnorderedElementsAre(
cobalt::Event(cobalt::EventType::kInteger,
cobalt_registry::kPreviousBootLogLastTimestampDeltaMetricId,
{cobalt_registry::FeedbackMetricDimensionProvider::Feedback},
*param.expected_delta_ms)));
} else {
EXPECT_THAT(ReceivedCobaltEvents(), IsEmpty());
}
}
} // namespace
} // namespace forensics::feedback