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 cuttlefish::monitor {
30 namespace {
31 
32 constexpr struct {
33   std::string_view match;   // Substring to match in the kernel logs
34   std::string_view prefix;  // Prefix value to output, describing the entry
35 } kInformationalPatterns[] = {
36     {"U-Boot ", "GUEST_UBOOT_VERSION: "},
37     {"] Linux version ", "GUEST_KERNEL_VERSION: "},
38     {"GUEST_BUILD_FINGERPRINT: ", "GUEST_BUILD_FINGERPRINT: "},
39 };
40 
41 enum EventFormat {
42   kBare,          // Just an event, no extra data
43   kKeyValuePair,  // <stage> <key>=<value>
44   kPrefix,        // <stage> <more data>
45 };
46 
47 constexpr struct {
48   std::string_view stage;  // substring in the log identifying the stage
49   Event event;             // emitted when the stage is encountered
50   EventFormat format;      // how the log message is formatted
51 } kStageTable[] = {
52     {kBootStartedMessage, Event::BootStarted, kBare},
53     {kBootPendingMessage, Event::BootPending, kPrefix},
54     {kBootCompletedMessage, Event::BootCompleted, kBare},
55     {kBootFailedMessage, Event::BootFailed, kPrefix},
56     {kMobileNetworkConnectedMessage, Event::MobileNetworkConnected, kBare},
57     {kWifiConnectedMessage, Event::WifiNetworkConnected, kBare},
58     {kEthernetConnectedMessage, Event::EthernetNetworkConnected, kBare},
59     {kAdbdStartedMessage, Event::AdbdStarted, kBare},
60     {kFastbootdStartedMessage, Event::FastbootStarted, kBare},
61     {kFastbootStartedMessage, Event::FastbootStarted, kBare},
62     {kScreenChangedMessage, Event::ScreenChanged, kKeyValuePair},
63     {kBootloaderLoadedMessage, Event::BootloaderLoaded, kBare},
64     {kKernelLoadedMessage, Event::KernelLoaded, kBare},
65     {kDisplayPowerModeChangedMessage, Event::DisplayPowerModeChanged,
66      kKeyValuePair},
67     {kHibernationExitMessage, Event::HibernationExited, kBare},
68     {kHibernationExitMessage, Event::AdbdStarted, kBare},
69 };
70 
ProcessSubscriptions(Json::Value message,std::vector<EventCallback> * subscribers)71 void ProcessSubscriptions(Json::Value message,
72                           std::vector<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 == SubscriptionAction::ContinueSubscription) {
79       ++idx;
80     } else {
81       // Cancel the subscription by swapping 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 
KernelLogServer(SharedFD pipe_fd,const std::string & log_name)92 KernelLogServer::KernelLogServer(SharedFD pipe_fd, const std::string& log_name)
93     : pipe_fd_(pipe_fd),
94       log_fd_(SharedFD::Open(log_name.c_str(), O_CREAT | O_RDWR | O_APPEND,
95                              0666)) {}
96 
BeforeSelect(SharedFDSet * fd_read) const97 void KernelLogServer::BeforeSelect(SharedFDSet* fd_read) const {
98   fd_read->Set(pipe_fd_);
99 }
100 
AfterSelect(const SharedFDSet & fd_read)101 void KernelLogServer::AfterSelect(const SharedFDSet& fd_read) {
102   if (fd_read.IsSet(pipe_fd_)) {
103     HandleIncomingMessage();
104   }
105 }
106 
SubscribeToEvents(EventCallback callback)107 void KernelLogServer::SubscribeToEvents(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) {
120     return false;
121   }
122   // Write the log to a file
123   if (log_fd_->Write(buf, ret) < 0) {
124     LOG(ERROR) << "Could not write kernel log to file: " << log_fd_->StrError();
125     return false;
126   }
127 
128   // Detect VIRTUAL_DEVICE_BOOT_*
129   for (ssize_t i=0; i<ret; i++) {
130     if ('\n' == buf[i]) {
131       for (auto& [match, prefix] : kInformationalPatterns) {
132         auto pos = line_.find(match);
133         if (std::string::npos != pos) {
134           LOG(INFO) << prefix << line_.substr(pos + match.size());
135         }
136       }
137       for (const auto& [stage, event, format] : kStageTable) {
138         auto pos = line_.find(stage);
139         if (std::string::npos != pos) {
140           // Log the stage
141           if (format == kPrefix) {
142             LOG(INFO) << line_.substr(pos);
143           } else {
144             LOG(INFO) << stage;
145           }
146 
147           Json::Value message;
148           message["event"] = event;
149           Json::Value metadata;
150 
151           if (format == kKeyValuePair) {
152             // Expect space-separated key=value pairs in the log message.
153             const auto& fields =
154                 android::base::Split(line_.substr(pos + stage.size()), " ");
155             for (std::string field : fields) {
156               field = android::base::Trim(field);
157               if (field.empty()) {
158                 // Expected; android::base::Split() always returns at least
159                 // one (possibly empty) string.
160                 LOG(DEBUG) << "Empty field for line: " << line_;
161                 continue;
162               }
163               const auto& keyvalue = android::base::Split(field, "=");
164               if (keyvalue.size() != 2) {
165                 LOG(WARNING) << "Field is not in key=value format: " << field;
166                 continue;
167               }
168               metadata[keyvalue[0]] = keyvalue[1];
169             }
170           }
171           message["metadata"] = metadata;
172           ProcessSubscriptions(message, &subscribers_);
173         }
174       }
175       line_.clear();
176     }
177     line_.append(1, buf[i]);
178   }
179 
180   return true;
181 }
182 
183 }  // namespace cuttlefish::monitor
184