1 // Copyright 2020 The Pigweed Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License"); you may not
4 // use this file except in compliance with the License. You may obtain a copy of
5 // the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11 // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12 // License for the specific language governing permissions and limitations under
13 // the License.
14
15 #include "pw_log_rpc/logs_rpc.h"
16
17 #include "pw_log/log.h"
18 #include "pw_log_proto/log.pwpb.h"
19 #include "pw_status/try.h"
20
21 namespace pw::log_rpc {
22 namespace {
23
GenerateDroppedEntryMessage(ByteSpan encode_buffer,size_t dropped_entries)24 Result<ConstByteSpan> GenerateDroppedEntryMessage(ByteSpan encode_buffer,
25 size_t dropped_entries) {
26 pw::protobuf::NestedEncoder nested_encoder(encode_buffer);
27 pw::log::LogEntry::Encoder encoder(&nested_encoder);
28 encoder.WriteDropped(dropped_entries);
29 return nested_encoder.Encode();
30 }
31
32 } // namespace
33
Get(ServerContext &,ConstByteSpan,rpc::RawServerWriter & writer)34 void Logs::Get(ServerContext&, ConstByteSpan, rpc::RawServerWriter& writer) {
35 response_writer_ = std::move(writer);
36 }
37
Flush()38 Status Logs::Flush() {
39 // If the response writer was not initialized or has since been closed,
40 // ignore the flush operation.
41 if (!response_writer_.open()) {
42 return OkStatus();
43 }
44
45 // If previous calls to flush resulted in dropped entries, generate a
46 // dropped entry message and write it before further log messages.
47 if (dropped_entries_ > 0) {
48 ByteSpan payload = response_writer_.PayloadBuffer();
49 Result dropped_log = GenerateDroppedEntryMessage(payload, dropped_entries_);
50 PW_TRY(dropped_log.status());
51 PW_TRY(response_writer_.Write(dropped_log.value()));
52 dropped_entries_ = 0;
53 }
54
55 // Write logs to the response writer. An important limitation of this
56 // implementation is that if this RPC call fails, the logs are lost -
57 // a subsequent call to the RPC will produce a drop count message.
58 ByteSpan payload = response_writer_.PayloadBuffer();
59 Result possible_logs = log_queue_.PopMultiple(payload);
60 PW_TRY(possible_logs.status());
61 if (possible_logs.value().entry_count == 0) {
62 return OkStatus();
63 }
64
65 Status status = response_writer_.Write(possible_logs.value().entries);
66 if (!status.ok()) {
67 // On a failure to send logs, track the dropped entries.
68 dropped_entries_ = possible_logs.value().entry_count;
69 return status;
70 }
71
72 return OkStatus();
73 }
74
75 } // namespace pw::log_rpc
76