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       Result<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                    << read_result.error().FormatForEnv();
70         break;
71       } else if (!(*read_result)) {
72         LOG(ERROR) << "EOF from kernel_log_monitor";
73         break;
74       }
75 
76       if ((*read_result)->event == monitor::Event::BootStarted) {
77         Json::Value message;
78         message["event"] = kBootStartedMessage;
79         DeliverEvent(message);
80       }
81       if ((*read_result)->event == monitor::Event::BootCompleted) {
82         Json::Value message;
83         message["event"] = kBootCompletedMessage;
84         DeliverEvent(message);
85       }
86       if ((*read_result)->event == monitor::Event::ScreenChanged) {
87         Json::Value message;
88         message["event"] = kScreenChangedMessage;
89         message["metadata"] = (*read_result)->metadata;
90         DeliverEvent(message);
91       }
92       if ((*read_result)->event == monitor::Event::DisplayPowerModeChanged) {
93         Json::Value message;
94         message["event"] = kDisplayPowerModeChangedMessage;
95         message["metadata"] = (*read_result)->metadata;
96         DeliverEvent(message);
97       }
98     }
99   }
100 }
101 
AddSubscriber(std::function<void (const Json::Value &)> subscriber)102 int KernelLogEventsHandler::AddSubscriber(
103     std::function<void(const Json::Value&)> subscriber) {
104   std::lock_guard<std::mutex> lock(subscribers_mtx_);
105   for (const auto& event : last_events_) {
106     // Deliver the last event of each type to the new subscriber so that it can
107     // show the correct state.
108     subscriber(event);
109   }
110   subscribers_[++last_subscriber_id_] = subscriber;
111   return last_subscriber_id_;
112 }
113 
Unsubscribe(int subscriber_id)114 void KernelLogEventsHandler::Unsubscribe(int subscriber_id) {
115   std::lock_guard<std::mutex> lock(subscribers_mtx_);
116   subscribers_.erase(subscriber_id);
117 }
118 
DeliverEvent(const Json::Value & event)119 void KernelLogEventsHandler::DeliverEvent(const Json::Value& event) {
120   std::lock_guard<std::mutex> lock(subscribers_mtx_);
121   // event["event"] is actually the type of the event.
122   // This would be more efficient with a set, but a list maintains the order in
123   // which events arrived. And for just a handful of elements the list can
124   // actually perform better.
125   for (auto it = last_events_.begin();
126        it != last_events_.end(); it++) {
127     if ((*it)["event"].asString() == event["event"].asString()) {
128       last_events_.erase(it);
129       break;
130     }
131   }
132   last_events_.push_back(event);
133   for (const auto& entry : subscribers_) {
134     entry.second(event);
135   }
136 }
137 
138 }  // namespace cuttlefish
139