• 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,
57      kBare},
58     {cuttlefish::kWifiConnectedMessage, Event::WifiNetworkConnected, kBare},
59     {cuttlefish::kEthernetConnectedMessage, Event::EthernetNetworkConnected,
60      kBare},
61     // TODO(b/131864854): Replace this with a string less likely to change
62     {"init: starting service 'adbd'...", Event::AdbdStarted, kBare},
63     {cuttlefish::kScreenChangedMessage, Event::ScreenChanged, kKeyValuePair},
64     {cuttlefish::kBootloaderLoadedMessage, Event::BootloaderLoaded, kBare},
65     {cuttlefish::kKernelLoadedMessage, Event::KernelLoaded, kBare},
66     {cuttlefish::kDisplayPowerModeChangedMessage,
67      monitor::Event::DisplayPowerModeChanged, kKeyValuePair},
68 };
69 
ProcessSubscriptions(Json::Value message,std::vector<monitor::EventCallback> * subscribers)70 void ProcessSubscriptions(
71     Json::Value message,
72     std::vector<monitor::EventCallback>* subscribers) {
73   auto active_subscription_count = subscribers->size();
74   std::size_t idx = 0;
75   while (idx < active_subscription_count) {
76     // Call the callback
77     auto action = (*subscribers)[idx](message);
78     if (action == monitor::SubscriptionAction::ContinueSubscription) {
79       ++idx;
80     } else {
81       // Cancel the subscription by swaping it with the last active subscription
82       // and decreasing the active subscription count
83       --active_subscription_count;
84       std::swap((*subscribers)[idx], (*subscribers)[active_subscription_count]);
85     }
86   }
87   // Keep only the active subscriptions
88   subscribers->resize(active_subscription_count);
89 }
90 }  // namespace
91 
92 namespace monitor {
KernelLogServer(cuttlefish::SharedFD pipe_fd,const std::string & log_name,bool deprecated_boot_completed)93 KernelLogServer::KernelLogServer(cuttlefish::SharedFD pipe_fd,
94                                  const std::string& log_name,
95                                  bool deprecated_boot_completed)
96     : pipe_fd_(pipe_fd),
97       log_fd_(cuttlefish::SharedFD::Open(log_name.c_str(), O_CREAT | O_RDWR | O_APPEND, 0666)),
98       deprecated_boot_completed_(deprecated_boot_completed) {}
99 
BeforeSelect(cuttlefish::SharedFDSet * fd_read) const100 void KernelLogServer::BeforeSelect(cuttlefish::SharedFDSet* fd_read) const {
101   fd_read->Set(pipe_fd_);
102 }
103 
AfterSelect(const cuttlefish::SharedFDSet & fd_read)104 void KernelLogServer::AfterSelect(const cuttlefish::SharedFDSet& fd_read) {
105   if (fd_read.IsSet(pipe_fd_)) {
106     HandleIncomingMessage();
107   }
108 }
109 
SubscribeToEvents(monitor::EventCallback callback)110 void KernelLogServer::SubscribeToEvents(monitor::EventCallback callback) {
111   subscribers_.push_back(callback);
112 }
113 
HandleIncomingMessage()114 bool KernelLogServer::HandleIncomingMessage() {
115   const size_t buf_len = 256;
116   char buf[buf_len];
117   ssize_t ret = pipe_fd_->Read(buf, buf_len);
118   if (ret < 0) {
119     LOG(ERROR) << "Could not read kernel logs: " << pipe_fd_->StrError();
120     return false;
121   }
122   if (ret == 0) return false;
123   // Write the log to a file
124   if (log_fd_->Write(buf, ret) < 0) {
125     LOG(ERROR) << "Could not write kernel log to file: " << log_fd_->StrError();
126     return false;
127   }
128 
129   // Detect VIRTUAL_DEVICE_BOOT_*
130   for (ssize_t i=0; i<ret; i++) {
131     if ('\n' == buf[i]) {
132       for (auto& [match, prefix] : kInformationalPatterns) {
133         auto pos = line_.find(match);
134         if (std::string::npos != pos) {
135           LOG(INFO) << prefix << line_.substr(pos + match.size());
136         }
137       }
138       for (const auto& [stage, event, format] : kStageTable) {
139         auto pos = line_.find(stage);
140         if (std::string::npos != pos) {
141           // Log the stage
142           LOG(INFO) << stage;
143 
144           Json::Value message;
145           message["event"] = event;
146           Json::Value metadata;
147 
148           if (format == kKeyValuePair) {
149             // Expect space-separated key=value pairs in the log message.
150             const auto& fields =
151                 android::base::Split(line_.substr(pos + stage.size()), " ");
152             for (std::string field : fields) {
153               field = android::base::Trim(field);
154               if (field.empty()) {
155                 // Expected; android::base::Split() always returns at least
156                 // one (possibly empty) string.
157                 LOG(DEBUG) << "Empty field for line: " << line_;
158                 continue;
159               }
160               const auto& keyvalue = android::base::Split(field, "=");
161               if (keyvalue.size() != 2) {
162                 LOG(WARNING) << "Field is not in key=value format: " << field;
163                 continue;
164               }
165               metadata[keyvalue[0]] = keyvalue[1];
166             }
167           }
168           message["metadata"] = metadata;
169           ProcessSubscriptions(message, &subscribers_);
170 
171           //TODO(b/69417553) Remove this when our clients have transitioned to the
172           // new boot completed
173           if (deprecated_boot_completed_) {
174             // Write to host kernel log
175             FILE* log = popen("/usr/bin/sudo /usr/bin/tee /dev/kmsg", "w");
176             fprintf(log, "%s\n", std::string(stage).c_str());
177             fclose(log);
178           }
179         }
180       }
181       line_.clear();
182     }
183     line_.append(1, buf[i]);
184   }
185 
186   return true;
187 }
188 
189 }  // namespace monitor
190