1 /*
2  * Copyright (C) 2020 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/frontend/webrtc/kernel_log_events_handler.h"
18 
19 #include <android-base/logging.h>
20 
21 #include <common/libs/fs/shared_select.h>
22 #include <host/commands/kernel_log_monitor/kernel_log_server.h>
23 #include <host/commands/kernel_log_monitor/utils.h>
24 #include <host/libs/config/cuttlefish_config.h>
25 
26 using namespace android;
27 
28 namespace cuttlefish {
29 
KernelLogEventsHandler(SharedFD kernel_log_fd)30 KernelLogEventsHandler::KernelLogEventsHandler(
31     SharedFD kernel_log_fd)
32     : kernel_log_fd_(kernel_log_fd),
33       eventfd_(SharedFD::Event()),
34       running_(true),
35       read_thread_([this]() { ReadLoop(); }) {}
36 
~KernelLogEventsHandler()37 KernelLogEventsHandler::~KernelLogEventsHandler() {
38   running_ = false;
39   eventfd_->EventfdWrite(1);
40   read_thread_.join();
41 }
42 
ReadLoop()43 void KernelLogEventsHandler::ReadLoop() {
44   CHECK(eventfd_->IsOpen()) << "Failed to create event fd: "
45                            << eventfd_->StrError();
46   while (running_) {
47     SharedFDSet read_set;
48     read_set.Set(eventfd_);
49     read_set.Set(kernel_log_fd_);
50     auto select_ret = Select(&read_set, nullptr, nullptr, nullptr);
51     if (select_ret < 0) {
52       LOG(ERROR) << "Error on select call";
53       break;
54     }
55     if (read_set.IsSet(eventfd_)) {
56       eventfd_t evt;
57       (void)eventfd_->EventfdRead(&evt);
58       if (!running_) {
59         // There won't be anyone listening for kernel log events if the thread
60         // was asked to stop, so break out of the loop without reading.
61         break;
62       }
63     }
64     if (read_set.IsSet(kernel_log_fd_)) {
65       std::optional<monitor::ReadEventResult> read_result =
66           monitor::ReadEvent(kernel_log_fd_);
67       if (!read_result) {
68         LOG(ERROR) << "Failed to read kernel log event: "
69                    << kernel_log_fd_->StrError();
70         break;
71       }
72 
73       if (read_result->event == monitor::Event::BootStarted) {
74         Json::Value message;
75         message["event"] = kBootStartedMessage;
76         DeliverEvent(message);
77       }
78       if (read_result->event == monitor::Event::BootCompleted) {
79         Json::Value message;
80         message["event"] = kBootCompletedMessage;
81         DeliverEvent(message);
82       }
83       if (read_result->event == monitor::Event::ScreenChanged) {
84         Json::Value message;
85         message["event"] = kScreenChangedMessage;
86         message["metadata"] = read_result->metadata;
87         DeliverEvent(message);
88       }
89       if (read_result->event == monitor::Event::DisplayPowerModeChanged) {
90         Json::Value message;
91         message["event"] = kDisplayPowerModeChangedMessage;
92         message["metadata"] = read_result->metadata;
93         DeliverEvent(message);
94       }
95     }
96   }
97 }
98 
AddSubscriber(std::function<void (const Json::Value &)> subscriber)99 int KernelLogEventsHandler::AddSubscriber(
100     std::function<void(const Json::Value&)> subscriber) {
101   std::lock_guard<std::mutex> lock(subscribers_mtx_);
102   for (const auto& event : last_events_) {
103     // Deliver the last event of each type to the new subscriber so that it can
104     // show the correct state.
105     subscriber(event);
106   }
107   subscribers_[++last_subscriber_id_] = subscriber;
108   return last_subscriber_id_;
109 }
110 
Unsubscribe(int subscriber_id)111 void KernelLogEventsHandler::Unsubscribe(int subscriber_id) {
112   std::lock_guard<std::mutex> lock(subscribers_mtx_);
113   subscribers_.erase(subscriber_id);
114 }
115 
DeliverEvent(const Json::Value & event)116 void KernelLogEventsHandler::DeliverEvent(const Json::Value& event) {
117   std::lock_guard<std::mutex> lock(subscribers_mtx_);
118   // event["event"] is actually the type of the event.
119   // This would be more efficient with a set, but a list maintains the order in
120   // which events arrived. And for just a handful of elements the list can
121   // actually perform better.
122   for (auto it = last_events_.begin();
123        it != last_events_.end(); it++) {
124     if ((*it)["event"].asString() == event["event"].asString()) {
125       last_events_.erase(it);
126       break;
127     }
128   }
129   last_events_.push_back(event);
130   for (const auto& entry : subscribers_) {
131     entry.second(event);
132   }
133 }
134 
135 }  // namespace cuttlefish
136