|
| 1 | +/* |
| 2 | + * Copyright (C) 2026 The Android Open Source Project |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | + |
| 17 | +#include "cuttlefish/host/commands/cvd/cli/commands/monitor.h" |
| 18 | + |
| 19 | +#include <fcntl.h> |
| 20 | +#include <sys/types.h> |
| 21 | +#include <unistd.h> |
| 22 | + |
| 23 | +#include <algorithm> |
| 24 | +#include <chrono> |
| 25 | +#include <cstddef> |
| 26 | +#include <cstdio> |
| 27 | +#include <cstring> |
| 28 | +#include <iostream> |
| 29 | +#include <memory> |
| 30 | +#include <sstream> |
| 31 | +#include <string> |
| 32 | +#include <thread> |
| 33 | +#include <utility> |
| 34 | +#include <vector> |
| 35 | + |
| 36 | +#include "absl/log/check.h" |
| 37 | +#include "absl/strings/cord.h" |
| 38 | +#include "absl/strings/str_cat.h" |
| 39 | +#include "absl/strings/str_replace.h" |
| 40 | +#include "absl/strings/str_split.h" |
| 41 | + |
| 42 | +#include "cuttlefish/common/libs/fs/shared_buf.h" |
| 43 | +#include "cuttlefish/common/libs/fs/shared_fd.h" |
| 44 | +#include "cuttlefish/host/commands/cvd/cli/command_request.h" |
| 45 | +#include "cuttlefish/host/commands/cvd/cli/commands/command_handler.h" |
| 46 | +#include "cuttlefish/host/commands/cvd/cli/selector/selector.h" |
| 47 | +#include "cuttlefish/host/commands/cvd/cli/types.h" |
| 48 | +#include "cuttlefish/host/commands/cvd/cli/utils.h" |
| 49 | +#include "cuttlefish/host/commands/cvd/instances/instance_manager.h" |
| 50 | +#include "cuttlefish/result/result.h" |
| 51 | + |
| 52 | +namespace cuttlefish { |
| 53 | + |
| 54 | +namespace { |
| 55 | + |
| 56 | +Result<std::vector<std::string>> GetLastNLines(SharedFD fd, size_t n) { |
| 57 | + off_t file_size = fd->LSeek(0, SEEK_END); |
| 58 | + CF_EXPECT(file_size != -1, "Failed to seek to end of file"); |
| 59 | + |
| 60 | + absl::Cord accumulated_data; |
| 61 | + off_t offset = file_size; |
| 62 | + size_t newline_count = 0; |
| 63 | + |
| 64 | + while (offset > 0 && newline_count < n + 1) { |
| 65 | + static constexpr off_t kChunkSize = 4096; |
| 66 | + size_t to_read = std::min(kChunkSize, offset); |
| 67 | + offset -= to_read; |
| 68 | + fd->LSeek(offset, SEEK_SET); |
| 69 | + |
| 70 | + std::string chunk(to_read, '\0'); |
| 71 | + ssize_t bytes_read = ReadExact(fd, &chunk); |
| 72 | + CF_EXPECTF(bytes_read == static_cast<ssize_t>(to_read), "Read failed: '{}'", |
| 73 | + fd->StrError()); |
| 74 | + |
| 75 | + newline_count += std::count(chunk.begin(), chunk.end(), '\n'); |
| 76 | + accumulated_data.Prepend(std::move(chunk)); |
| 77 | + } |
| 78 | + |
| 79 | + std::vector<std::string> all_lines = |
| 80 | + absl::StrSplit(std::string(accumulated_data), '\n'); |
| 81 | + |
| 82 | + // Handle trailing newline |
| 83 | + if (!all_lines.empty() && all_lines.back().empty()) { |
| 84 | + all_lines.pop_back(); |
| 85 | + } |
| 86 | + |
| 87 | + std::vector<std::string> result; |
| 88 | + size_t start_idx = all_lines.size() > n ? all_lines.size() - n : 0; |
| 89 | + for (size_t i = start_idx; i < all_lines.size(); ++i) { |
| 90 | + result.push_back(all_lines[i]); |
| 91 | + } |
| 92 | + |
| 93 | + return result; |
| 94 | +} |
| 95 | + |
| 96 | +} // namespace |
| 97 | + |
| 98 | +LogMonitorDisplay::LogMonitorDisplay(size_t width) |
| 99 | + : width_(width), total_lines_drawn_(0) {} |
| 100 | + |
| 101 | +void LogMonitorDisplay::DrawFile(SharedFD fd, const std::string& title) { |
| 102 | + std::vector<std::string> lines; |
| 103 | + if (fd->IsOpen()) { |
| 104 | + Result<std::vector<std::string>> lines_result = GetLastNLines(fd, 10); |
| 105 | + if (lines_result.ok()) { |
| 106 | + lines = *lines_result; |
| 107 | + } else { |
| 108 | + lines.push_back(absl::StrCat("Failed to read ", title, ":")); |
| 109 | + std::string error_str = |
| 110 | + lines_result.error().FormatForEnv(/*color=*/false); |
| 111 | + for (const auto& el : absl::StrSplit(error_str, '\n')) { |
| 112 | + if (!el.empty()) { |
| 113 | + lines.push_back(std::string(el)); |
| 114 | + } |
| 115 | + } |
| 116 | + } |
| 117 | + } else { |
| 118 | + lines.push_back(absl::StrCat("Failed to read ", title, ": File not open")); |
| 119 | + lines.push_back(absl::StrCat("Error: ", fd->StrError())); |
| 120 | + } |
| 121 | + |
| 122 | + while (lines.size() < 10) { |
| 123 | + lines.push_back(""); |
| 124 | + } |
| 125 | + |
| 126 | + DrawBorderedText(lines, title); |
| 127 | +} |
| 128 | + |
| 129 | +std::string LogMonitorDisplay::Finalize() { |
| 130 | + CHECK_GE(width_, 2); |
| 131 | + ss_ << "+" << std::string(width_ - 2, '-') << "+\n"; |
| 132 | + total_lines_drawn_++; |
| 133 | + return ss_.str(); |
| 134 | +} |
| 135 | + |
| 136 | +int LogMonitorDisplay::TotalLinesDrawn() const { return total_lines_drawn_; } |
| 137 | + |
| 138 | +void LogMonitorDisplay::DrawBorderedText(const std::vector<std::string>& lines, |
| 139 | + const std::string& title) { |
| 140 | + std::string top_border = absl::StrCat("+--", title, " "); |
| 141 | + CHECK_GE(width_, 2); |
| 142 | + top_border.resize(width_ - 1, '-'); |
| 143 | + ss_ << top_border << "+\n"; |
| 144 | + |
| 145 | + for (std::string line : lines) { |
| 146 | + absl::StrReplaceAll({{"\t", " "}, {"\r", ""}, {"\n", ""}}, &line); |
| 147 | + |
| 148 | + line.resize(width_ - 2, ' '); |
| 149 | + ss_ << "|" << line << "|\n"; |
| 150 | + } |
| 151 | + total_lines_drawn_ += 1 + lines.size(); |
| 152 | +} |
| 153 | + |
| 154 | +namespace { |
| 155 | + |
| 156 | +constexpr char kSummaryHelpText[] = |
| 157 | + "Monitor device logs (launcher, kernel, and logcat) in real-time."; |
| 158 | +constexpr char kDetailedHelpText[] = |
| 159 | + R"(monitor: Monitors a particular device by displaying the last 10 lines of its logs. |
| 160 | +It requires an interactive terminal and will continuously update the display every 50ms. |
| 161 | +
|
| 162 | +It displays: |
| 163 | +- launcher.log |
| 164 | +- kernel.log |
| 165 | +- logcat |
| 166 | +
|
| 167 | +Usage: |
| 168 | + cvd [selector options] monitor |
| 169 | +)"; |
| 170 | + |
| 171 | +constexpr char kMonitorCmd[] = "monitor"; |
| 172 | + |
| 173 | +void ClearLastNLines(int n) { |
| 174 | + if (n > 0) { |
| 175 | + // Move cursor up N lines and clear to end of screen |
| 176 | + std::cout << "\033[" << n << "A\033[J" << std::flush; |
| 177 | + } |
| 178 | +} |
| 179 | + |
| 180 | +class CvdMonitorCommandHandler : public CvdCommandHandler { |
| 181 | + public: |
| 182 | + CvdMonitorCommandHandler(InstanceManager& instance_manager) |
| 183 | + : instance_manager_{instance_manager} {} |
| 184 | + |
| 185 | + Result<void> Handle(const CommandRequest& request) override { |
| 186 | + CF_EXPECT(CanHandle(request)); |
| 187 | + |
| 188 | + CF_EXPECT(isatty(0), |
| 189 | + "The monitor command requires an interactive terminal."); |
| 190 | + |
| 191 | + auto [instance, unused] = |
| 192 | + CF_EXPECT(selector::SelectInstance(instance_manager_, request), |
| 193 | + "Unable to select an instance"); |
| 194 | + |
| 195 | + std::string kernel_log = instance.instance_dir() + "/logs/kernel.log"; |
| 196 | + std::string launcher_log = instance.instance_dir() + "/logs/launcher.log"; |
| 197 | + std::string logcat = instance.instance_dir() + "/logs/logcat"; |
| 198 | + |
| 199 | + SharedFD kernel_fd; |
| 200 | + SharedFD launcher_fd; |
| 201 | + SharedFD logcat_fd; |
| 202 | + |
| 203 | + while (true) { |
| 204 | + if (!kernel_fd->IsOpen()) { |
| 205 | + kernel_fd = SharedFD::Open(kernel_log, O_RDONLY); |
| 206 | + } |
| 207 | + if (!launcher_fd->IsOpen()) { |
| 208 | + launcher_fd = SharedFD::Open(launcher_log, O_RDONLY); |
| 209 | + } |
| 210 | + if (!logcat_fd->IsOpen()) { |
| 211 | + logcat_fd = SharedFD::Open(logcat, O_RDONLY); |
| 212 | + } |
| 213 | + |
| 214 | + Result<TerminalSize> term_size_result = GetTerminalSize(); |
| 215 | + int width = 79; // Default fallback width (80 - 1) |
| 216 | + if (term_size_result.ok()) { |
| 217 | + width = term_size_result->columns - 1; |
| 218 | + } |
| 219 | + LogMonitorDisplay display(width); |
| 220 | + |
| 221 | + display.DrawFile(launcher_fd, "launcher.log"); |
| 222 | + display.DrawFile(kernel_fd, "kernel.log"); |
| 223 | + display.DrawFile(logcat_fd, "logcat"); |
| 224 | + |
| 225 | + std::cout << display.Finalize() << std::flush; |
| 226 | + |
| 227 | + // Wait a bit before clearing and redrawing |
| 228 | + std::this_thread::sleep_for(std::chrono::milliseconds(50)); |
| 229 | + ClearLastNLines(display.TotalLinesDrawn()); |
| 230 | + } |
| 231 | + |
| 232 | + return {}; |
| 233 | + } |
| 234 | + |
| 235 | + cvd_common::Args CmdList() const override { return {kMonitorCmd}; } |
| 236 | + |
| 237 | + Result<std::string> SummaryHelp() const override { return kSummaryHelpText; } |
| 238 | + |
| 239 | + bool RequiresDeviceExists() const override { return true; } |
| 240 | + |
| 241 | + Result<std::string> DetailedHelp( |
| 242 | + const CommandRequest& request) const override { |
| 243 | + return kDetailedHelpText; |
| 244 | + } |
| 245 | + |
| 246 | + private: |
| 247 | + InstanceManager& instance_manager_; |
| 248 | +}; |
| 249 | + |
| 250 | +} // namespace |
| 251 | + |
| 252 | +std::unique_ptr<CvdCommandHandler> NewCvdMonitorCommandHandler( |
| 253 | + InstanceManager& instance_manager) { |
| 254 | + return std::unique_ptr<CvdCommandHandler>( |
| 255 | + new CvdMonitorCommandHandler(instance_manager)); |
| 256 | +} |
| 257 | + |
| 258 | +} // namespace cuttlefish |
0 commit comments