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/commands/kernel_log_monitor/utils.h"
18
19 #include <android-base/logging.h>
20
21 #include "common/libs/fs/shared_buf.h"
22
23 namespace monitor {
24
ReadEvent(cuttlefish::SharedFD fd)25 std::optional<ReadEventResult> ReadEvent(cuttlefish::SharedFD fd) {
26 size_t length;
27 ssize_t bytes_read = cuttlefish::ReadExactBinary(fd, &length);
28 if (bytes_read <= 0) {
29 LOG(ERROR) << "Failed to read event buffer size: " << fd->StrError();
30 return std::nullopt;
31 }
32 std::string buf(length, ' ');
33 bytes_read = cuttlefish::ReadExact(fd, &buf);
34 if (bytes_read <= 0) {
35 LOG(ERROR) << "Failed to read event buffer: " << fd->StrError();
36 return std::nullopt;
37 }
38
39 Json::CharReaderBuilder builder;
40 std::unique_ptr<Json::CharReader> reader(builder.newCharReader());
41 std::string errorMessage;
42 Json::Value message;
43 if (!reader->parse(&*buf.begin(), &*buf.end(), &message, &errorMessage)) {
44 LOG(ERROR) << "Unable to parse event JSON: " << errorMessage;
45 return std::nullopt;
46 }
47
48 ReadEventResult result = {
49 static_cast<monitor::Event>(message["event"].asInt()),
50 message["metadata"]
51 };
52 return result;
53 }
54
WriteEvent(cuttlefish::SharedFD fd,const Json::Value & event_message)55 bool WriteEvent(cuttlefish::SharedFD fd, const Json::Value& event_message) {
56 Json::StreamWriterBuilder factory;
57 std::string message_string = Json::writeString(factory, event_message);
58 size_t length = message_string.length();
59 ssize_t retval = cuttlefish::WriteAllBinary(fd, &length);
60 if (retval <= 0) {
61 LOG(ERROR) << "Failed to write event buffer size: " << fd->StrError();
62 return false;
63 }
64 retval = cuttlefish::WriteAll(fd, message_string);
65 if (retval <= 0) {
66 LOG(ERROR) << "Failed to write event buffer: " << fd->StrError();
67 return false;
68 }
69 return true;
70 }
71
72 } // namespace monitor
73