1 /*
2 * Copyright (C) 2022 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 "chre/core/telemetry_manager.h"
18
19 #include <pb_encode.h>
20
21 #include "chre/core/event_loop_manager.h"
22 #include "chre/platform/fatal_error.h"
23 #include "chre/platform/shared/host_protocol_chre.h"
24 #include "chre/util/macros.h"
25 #include "chre/util/nested_data_ptr.h"
26 #include "chre/util/time.h"
27 #include "core/chre_metrics.nanopb.h"
28
29 namespace chre {
30
31 namespace {
32
33 // !!!!!!!!!!!!!!!!!!!!!!!!!!!!! DISCLAIMER !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
34 // The metrics implemented in this class makes use of open-sourced PixelAtoms,
35 // but they are not Pixel-specific, and can be extended to OEM use. If you
36 // would like to use this code for telemetry purposes, please contact us for
37 // details.
38
39 //! Helper define macros for nanopb types.
40 #define CHREATOMS_GET(x) android_chre_metrics_##x
41 #define CHREATOMS_GET_PAL_TYPE(x) \
42 _android_chre_metrics_ChrePalType:: \
43 android_chre_metrics_ChrePalType_CHRE_PAL_TYPE_##x
44
45 // These IDs must be kept in sync with
46 // hardware/google/pixel/pixelstats/pixelatoms.proto.
47 constexpr uint32_t kEventQueueSnapshotReportedId = 105035;
48 constexpr uint32_t kPalOpenedFailedId = 105032;
49
sendMetricToHost(uint32_t atomId,const pb_field_t fields[],const void * data)50 void sendMetricToHost(uint32_t atomId, const pb_field_t fields[],
51 const void *data) {
52 size_t size;
53 if (!pb_get_encoded_size(&size, fields, data)) {
54 LOGE("Failed to get message size");
55 } else {
56 pb_byte_t *bytes = static_cast<pb_byte_t *>(memoryAlloc(size));
57 if (bytes == nullptr) {
58 LOG_OOM();
59 } else {
60 pb_ostream_t stream = pb_ostream_from_buffer(bytes, size);
61 if (!pb_encode(&stream, fields, data)) {
62 LOGE("Failed to metric error %s", PB_GET_ERROR(&stream));
63 } else {
64 HostCommsManager &manager =
65 EventLoopManagerSingleton::get()->getHostCommsManager();
66 if (!manager.sendMetricLog(atomId, bytes, size)) {
67 LOGE("Failed to send metric message");
68 }
69 }
70 memoryFree(bytes);
71 }
72 }
73 }
74
sendPalOpenFailedMetric(_android_chre_metrics_ChrePalType pal)75 void sendPalOpenFailedMetric(_android_chre_metrics_ChrePalType pal) {
76 _android_chre_metrics_ChrePalOpenFailed result =
77 CHREATOMS_GET(ChrePalOpenFailed_init_default);
78 result.has_pal = true;
79 result.pal = pal;
80 result.has_type = true;
81 result.type = _android_chre_metrics_ChrePalOpenFailed_Type::
82 android_chre_metrics_ChrePalOpenFailed_Type_INITIAL_OPEN;
83
84 sendMetricToHost(kPalOpenedFailedId, CHREATOMS_GET(ChrePalOpenFailed_fields),
85 &result);
86 }
87
sendEventLoopStats(uint32_t maxQueueSize,uint32_t meanQueueSize,uint32_t numDroppedEvents)88 void sendEventLoopStats(uint32_t maxQueueSize, uint32_t meanQueueSize,
89 uint32_t numDroppedEvents) {
90 _android_chre_metrics_ChreEventQueueSnapshotReported result =
91 CHREATOMS_GET(ChreEventQueueSnapshotReported_init_default);
92 result.has_snapshot_chre_get_time_ms = true;
93 result.snapshot_chre_get_time_ms =
94 SystemTime::getMonotonicTime().toRawNanoseconds() /
95 kOneMillisecondInNanoseconds;
96 result.has_max_event_queue_size = true;
97 result.max_event_queue_size = maxQueueSize;
98 result.has_mean_event_queue_size = true;
99 result.mean_event_queue_size = meanQueueSize;
100 result.has_num_dropped_events = true;
101 result.num_dropped_events = numDroppedEvents;
102
103 sendMetricToHost(kEventQueueSnapshotReportedId,
104 CHREATOMS_GET(ChreEventQueueSnapshotReported_fields),
105 &result);
106 }
107
toAtomPalType(TelemetryManager::PalType type)108 _android_chre_metrics_ChrePalType toAtomPalType(
109 TelemetryManager::PalType type) {
110 switch (type) {
111 case TelemetryManager::PalType::SENSOR:
112 return CHREATOMS_GET_PAL_TYPE(SENSOR);
113 case TelemetryManager::PalType::WIFI:
114 return CHREATOMS_GET_PAL_TYPE(WIFI);
115 case TelemetryManager::PalType::GNSS:
116 return CHREATOMS_GET_PAL_TYPE(GNSS);
117 case TelemetryManager::PalType::WWAN:
118 return CHREATOMS_GET_PAL_TYPE(WWAN);
119 case TelemetryManager::PalType::AUDIO:
120 return CHREATOMS_GET_PAL_TYPE(AUDIO);
121 case TelemetryManager::PalType::BLE:
122 return CHREATOMS_GET_PAL_TYPE(BLE);
123 case TelemetryManager::PalType::UNKNOWN:
124 default:
125 LOGW("Unknown PAL type %" PRIu8, type);
126 return CHREATOMS_GET_PAL_TYPE(UNKNOWN);
127 }
128 }
129
130 } // anonymous namespace
131
TelemetryManager()132 TelemetryManager::TelemetryManager() {
133 scheduleMetricTimer();
134 }
135
onPalOpenFailure(PalType type)136 void TelemetryManager::onPalOpenFailure(PalType type) {
137 auto callback = [](uint16_t /*type*/, void *data, void * /*extraData*/) {
138 _android_chre_metrics_ChrePalType palType =
139 toAtomPalType(NestedDataPtr<PalType>(data));
140
141 if (palType != CHREATOMS_GET_PAL_TYPE(UNKNOWN)) {
142 sendPalOpenFailedMetric(palType);
143 }
144 };
145
146 // Defer the metric sending callback to better ensure that the host can
147 // receive this message, as this method may be called prior to chre::init()
148 // completion.
149 EventLoopManagerSingleton::get()->deferCallback(
150 SystemCallbackType::DeferredMetricPostEvent, NestedDataPtr<PalType>(type),
151 callback);
152 }
153
collectSystemMetrics()154 void TelemetryManager::collectSystemMetrics() {
155 EventLoop &eventLoop = EventLoopManagerSingleton::get()->getEventLoop();
156 sendEventLoopStats(eventLoop.getMaxEventQueueSize(),
157 eventLoop.getMeanEventQueueSize(),
158 eventLoop.getNumEventsDropped());
159
160 scheduleMetricTimer();
161 }
162
scheduleMetricTimer()163 void TelemetryManager::scheduleMetricTimer() {
164 constexpr Seconds kDelay = Seconds(kOneDayInSeconds);
165 auto callback = [](uint16_t /* eventType */, void * /* data */,
166 void * /* extraData */) {
167 EventLoopManagerSingleton::get()
168 ->getTelemetryManager()
169 .collectSystemMetrics();
170 };
171 TimerHandle handle = EventLoopManagerSingleton::get()->setDelayedCallback(
172 SystemCallbackType::DeferredMetricPostEvent, nullptr /* data */, callback,
173 kDelay);
174 if (handle == CHRE_TIMER_INVALID) {
175 LOGE("Failed to set daily metric timer");
176 }
177 }
178
179 } // namespace chre
180