• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "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 
sendMetricToHost(uint32_t atomId,const pb_field_t fields[],const void * data)45 void sendMetricToHost(uint32_t atomId, const pb_field_t fields[],
46                       const void *data) {
47   size_t size;
48   if (!pb_get_encoded_size(&size, CHREATOMS_GET(ChrePalOpenFailed_fields),
49                            data)) {
50     LOGE("Failed to get message size");
51   } else {
52     pb_byte_t *bytes = static_cast<pb_byte_t *>(memoryAlloc(size));
53     if (bytes == nullptr) {
54       LOG_OOM();
55     } else {
56       pb_ostream_t stream = pb_ostream_from_buffer(bytes, size);
57       if (!pb_encode(&stream, CHREATOMS_GET(ChrePalOpenFailed_fields), data)) {
58         LOGE("Failed to metric error %s", PB_GET_ERROR(&stream));
59       } else {
60         HostCommsManager &manager =
61             EventLoopManagerSingleton::get()->getHostCommsManager();
62         if (!manager.sendMetricLog(CHREATOMS_GET(Atom_chre_pal_open_failed_tag),
63                                    bytes, size)) {
64           LOGE("Failed to send metric message");
65         }
66       }
67       memoryFree(bytes);
68     }
69   }
70 }
71 
sendPalOpenFailedMetric(_android_chre_metrics_ChrePalType pal)72 void sendPalOpenFailedMetric(_android_chre_metrics_ChrePalType pal) {
73   _android_chre_metrics_ChrePalOpenFailed result =
74       CHREATOMS_GET(ChrePalOpenFailed_init_default);
75   result.has_pal = true;
76   result.pal = pal;
77   result.has_type = true;
78   result.type = _android_chre_metrics_ChrePalOpenFailed_Type::
79       android_chre_metrics_ChrePalOpenFailed_Type_INITIAL_OPEN;
80 
81   sendMetricToHost(CHREATOMS_GET(Atom_chre_pal_open_failed_tag),
82                    CHREATOMS_GET(ChrePalOpenFailed_fields), &result);
83 }
84 
sendEventLoopStats(uint32_t maxQueueSize,uint32_t meanQueueSize,uint32_t numDroppedEvents)85 void sendEventLoopStats(uint32_t maxQueueSize, uint32_t meanQueueSize,
86                         uint32_t numDroppedEvents) {
87   _android_chre_metrics_ChreEventQueueSnapshotReported result =
88       CHREATOMS_GET(ChreEventQueueSnapshotReported_init_default);
89   result.has_snapshot_chre_get_time_ms = true;
90   result.snapshot_chre_get_time_ms =
91       SystemTime::getMonotonicTime().toRawNanoseconds() /
92       kOneMillisecondInNanoseconds;
93   result.has_max_event_queue_size = true;
94   result.max_event_queue_size = maxQueueSize;
95   result.has_mean_event_queue_size = true;
96   result.mean_event_queue_size = meanQueueSize;
97   result.has_num_dropped_events = true;
98   result.num_dropped_events = numDroppedEvents;
99 
100   sendMetricToHost(CHREATOMS_GET(Atom_chre_event_queue_snapshot_reported_tag),
101                    CHREATOMS_GET(ChreEventQueueSnapshotReported_fields),
102                    &result);
103 }
104 
toAtomPalType(TelemetryManager::PalType type)105 _android_chre_metrics_ChrePalType toAtomPalType(
106     TelemetryManager::PalType type) {
107   switch (type) {
108     case TelemetryManager::PalType::SENSOR:
109       return CHREATOMS_GET_PAL_TYPE(SENSOR);
110     case TelemetryManager::PalType::WIFI:
111       return CHREATOMS_GET_PAL_TYPE(WIFI);
112     case TelemetryManager::PalType::GNSS:
113       return CHREATOMS_GET_PAL_TYPE(GNSS);
114     case TelemetryManager::PalType::WWAN:
115       return CHREATOMS_GET_PAL_TYPE(WWAN);
116     case TelemetryManager::PalType::AUDIO:
117       return CHREATOMS_GET_PAL_TYPE(AUDIO);
118     case TelemetryManager::PalType::BLE:
119       return CHREATOMS_GET_PAL_TYPE(BLE);
120     case TelemetryManager::PalType::UNKNOWN:
121     default:
122       LOGW("Unknown PAL type %" PRIu8, type);
123       return CHREATOMS_GET_PAL_TYPE(UNKNOWN);
124   }
125 }
126 
127 }  // anonymous namespace
128 
TelemetryManager()129 TelemetryManager::TelemetryManager() {
130   scheduleMetricTimer();
131 }
132 
onPalOpenFailure(PalType type)133 void TelemetryManager::onPalOpenFailure(PalType type) {
134   auto callback = [](uint16_t /*type*/, void *data, void * /*extraData*/) {
135     _android_chre_metrics_ChrePalType palType =
136         toAtomPalType(NestedDataPtr<PalType>(data));
137 
138     if (palType != CHREATOMS_GET_PAL_TYPE(UNKNOWN)) {
139       sendPalOpenFailedMetric(palType);
140     }
141   };
142 
143   // Defer the metric sending callback to better ensure that the host can
144   // receive this message, as this method may be called prior to chre::init()
145   // completion.
146   EventLoopManagerSingleton::get()->deferCallback(
147       SystemCallbackType::DeferredMetricPostEvent, NestedDataPtr<PalType>(type),
148       callback);
149 }
150 
collectSystemMetrics()151 void TelemetryManager::collectSystemMetrics() {
152   EventLoop &eventLoop = EventLoopManagerSingleton::get()->getEventLoop();
153   sendEventLoopStats(eventLoop.getMaxEventQueueSize(),
154                      eventLoop.getMeanEventQueueSize(),
155                      eventLoop.getNumEventsDropped());
156 
157   scheduleMetricTimer();
158 }
159 
scheduleMetricTimer()160 void TelemetryManager::scheduleMetricTimer() {
161   constexpr Seconds kDelay = Seconds(60 * 60 * 24);  // 24 hours
162   auto callback = [](uint16_t /* eventType */, void * /* data */,
163                      void * /* extraData */) {
164     EventLoopManagerSingleton::get()
165         ->getTelemetryManager()
166         .collectSystemMetrics();
167   };
168   TimerHandle handle = EventLoopManagerSingleton::get()->setDelayedCallback(
169       SystemCallbackType::DeferredMetricPostEvent, nullptr /* data */, callback,
170       kDelay);
171   if (handle == CHRE_TIMER_INVALID) {
172     LOGE("Failed to set daily metric timer");
173   }
174 }
175 
176 }  // namespace chre
177