• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2017 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 "host/commands/kernel_log_monitor/kernel_log_server.h"
18 
19 #include <string>
20 #include <tuple>
21 #include <utility>
22 
23 #include <android-base/logging.h>
24 #include <android-base/strings.h>
25 #include <netinet/in.h>
26 #include "common/libs/fs/shared_select.h"
27 #include "host/libs/config/cuttlefish_config.h"
28 
29 namespace {
30 
31 using cuttlefish::SharedFD;
32 using monitor::Event;
33 
34 constexpr struct {
35   std::string_view match;   // Substring to match in the kernel logs
36   std::string_view prefix;  // Prefix value to output, describing the entry
37 } kInformationalPatterns[] = {
38     {"U-Boot ", "GUEST_UBOOT_VERSION: "},
39     {"] Linux version ", "GUEST_KERNEL_VERSION: "},
40     {"GUEST_BUILD_FINGERPRINT: ", "GUEST_BUILD_FINGERPRINT: "},
41 };
42 
43 enum EventFormat {
44   kBare,          // Just an event, no extra data
45   kKeyValuePair,  // <stage> <key>=<value>
46 };
47 
48 constexpr struct {
49   std::string_view stage;  // substring in the log identifying the stage
50   Event event;             // emitted when the stage is encountered
51   EventFormat format;      // how the log message is formatted
52 } kStageTable[] = {
53     {cuttlefish::kBootStartedMessage, Event::BootStarted, kBare},
54     {cuttlefish::kBootCompletedMessage, Event::BootCompleted, kBare},
55     {cuttlefish::kBootFailedMessage, Event::BootFailed, kKeyValuePair},
56     {cuttlefish::kMobileNetworkConnectedMessage, Event::MobileNetworkConnected, kBare},
57     {cuttlefish::kWifiConnectedMessage, Event::WifiNetworkConnected, kBare},
58     {cuttlefish::kEthernetConnectedMessage, Event::EthernetNetworkConnected, kBare},
59     {cuttlefish::kAdbdStartedMessage, Event::AdbdStarted, kBare},
60     {cuttlefish::kFastbootdStartedMessage, Event::FastbootdStarted, kBare},
61     {cuttlefish::kScreenChangedMessage, Event::ScreenChanged, kKeyValuePair},
62     {cuttlefish::kBootloaderLoadedMessage, Event::BootloaderLoaded, kBare},
63     {cuttlefish::kKernelLoadedMessage, Event::KernelLoaded, kBare},
64     {cuttlefish::kDisplayPowerModeChangedMessage,
65      monitor::Event::DisplayPowerModeChanged, kKeyValuePair},
66 };
67 
ProcessSubscriptions(Json::Value message,std::vector<monitor::EventCallback> * subscribers)68 void ProcessSubscriptions(
69     Json::Value message,
70     std::vector<monitor::EventCallback>* subscribers) {
71   auto active_subscription_count = subscribers->size();
72   std::size_t idx = 0;
73   while (idx < active_subscription_count) {
74     // Call the callback
75     auto action = (*subscribers)[idx](message);
76     if (action == monitor::SubscriptionAction::ContinueSubscription) {
77       ++idx;
78     } else {
79       // Cancel the subscription by swaping it with the last active subscription
80       // and decreasing the active subscription count
81       --active_subscription_count;
82       std::swap((*subscribers)[idx], (*subscribers)[active_subscription_count]);
83     }
84   }
85   // Keep only the active subscriptions
86   subscribers->resize(active_subscription_count);
87 }
88 }  // namespace
89 
90 namespace monitor {
KernelLogServer(cuttlefish::SharedFD pipe_fd,const std::string & log_name)91 KernelLogServer::KernelLogServer(cuttlefish::SharedFD pipe_fd,
92                                  const std::string& log_name)
93     : pipe_fd_(pipe_fd),
94       log_fd_(cuttlefish::SharedFD::Open(log_name.c_str(),
95                                          O_CREAT | O_RDWR | O_APPEND, 0666)) {}
96 
BeforeSelect(cuttlefish::SharedFDSet * fd_read) const97 void KernelLogServer::BeforeSelect(cuttlefish::SharedFDSet* fd_read) const {
98   fd_read->Set(pipe_fd_);
99 }
100 
AfterSelect(const cuttlefish::SharedFDSet & fd_read)101 void KernelLogServer::AfterSelect(const cuttlefish::SharedFDSet& fd_read) {
102   if (fd_read.IsSet(pipe_fd_)) {
103     HandleIncomingMessage();
104   }
105 }
106 
SubscribeToEvents(monitor::EventCallback callback)107 void KernelLogServer::SubscribeToEvents(monitor::EventCallback callback) {
108   subscribers_.push_back(callback);
109 }
110 
HandleIncomingMessage()111 bool KernelLogServer::HandleIncomingMessage() {
112   const size_t buf_len = 256;
113   char buf[buf_len];
114   ssize_t ret = pipe_fd_->Read(buf, buf_len);
115   if (ret < 0) {
116     LOG(ERROR) << "Could not read kernel logs: " << pipe_fd_->StrError();
117     return false;
118   }
119   if (ret == 0) return false;
120   // Write the log to a file
121   if (log_fd_->Write(buf, ret) < 0) {
122     LOG(ERROR) << "Could not write kernel log to file: " << log_fd_->StrError();
123     return false;
124   }
125 
126   // Detect VIRTUAL_DEVICE_BOOT_*
127   for (ssize_t i=0; i<ret; i++) {
128     if ('\n' == buf[i]) {
129       for (auto& [match, prefix] : kInformationalPatterns) {
130         auto pos = line_.find(match);
131         if (std::string::npos != pos) {
132           LOG(INFO) << prefix << line_.substr(pos + match.size());
133         }
134       }
135       for (const auto& [stage, event, format] : kStageTable) {
136         auto pos = line_.find(stage);
137         if (std::string::npos != pos) {
138           // Log the stage
139           LOG(INFO) << stage;
140 
141           Json::Value message;
142           message["event"] = event;
143           Json::Value metadata;
144 
145           if (format == kKeyValuePair) {
146             // Expect space-separated key=value pairs in the log message.
147             const auto& fields =
148                 android::base::Split(line_.substr(pos + stage.size()), " ");
149             for (std::string field : fields) {
150               field = android::base::Trim(field);
151               if (field.empty()) {
152                 // Expected; android::base::Split() always returns at least
153                 // one (possibly empty) string.
154                 LOG(DEBUG) << "Empty field for line: " << line_;
155                 continue;
156               }
157               const auto& keyvalue = android::base::Split(field, "=");
158               if (keyvalue.size() != 2) {
159                 LOG(WARNING) << "Field is not in key=value format: " << field;
160                 continue;
161               }
162               metadata[keyvalue[0]] = keyvalue[1];
163             }
164           }
165           message["metadata"] = metadata;
166           ProcessSubscriptions(message, &subscribers_);
167         }
168       }
169       line_.clear();
170     }
171     line_.append(1, buf[i]);
172   }
173 
174   return true;
175 }
176 
177 }  // namespace monitor
178