xref: /aosp_15_r20/frameworks/native/services/inputflinger/InputDeviceMetricsCollector.cpp (revision 38e8c45f13ce32b0dcecb25141ffecaf386fa17f)
1 /*
2  * Copyright 2023 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 #define LOG_TAG "InputDeviceMetricsCollector"
18 #include "InputDeviceMetricsCollector.h"
19 
20 #include "InputDeviceMetricsSource.h"
21 
22 #include <android-base/stringprintf.h>
23 #include <input/PrintTools.h>
24 
25 namespace android {
26 
27 using android::base::StringPrintf;
28 using std::chrono::nanoseconds;
29 using std::chrono_literals::operator""ns;
30 
31 namespace {
32 
33 constexpr nanoseconds DEFAULT_USAGE_SESSION_TIMEOUT = std::chrono::minutes(2);
34 
35 /**
36  * Log debug messages about metrics events logged to statsd.
37  * Enable this via "adb shell setprop log.tag.InputDeviceMetricsCollector DEBUG" (requires restart)
38  */
39 const bool DEBUG = __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG, ANDROID_LOG_INFO);
40 
41 constexpr size_t INTERACTIONS_QUEUE_CAPACITY = 500;
42 
linuxBusToInputDeviceBusEnum(int32_t linuxBus,bool isUsiStylus)43 int32_t linuxBusToInputDeviceBusEnum(int32_t linuxBus, bool isUsiStylus) {
44     if (isUsiStylus) {
45         // This is a stylus connected over the Universal Stylus Initiative (USI) protocol.
46         // For metrics purposes, we treat this protocol as a separate bus.
47         return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__USI;
48     }
49 
50     // When adding cases to this switch, also add them to the copy of this method in
51     // TouchpadInputMapper.cpp.
52     // TODO(b/286394420): deduplicate this method with the one in TouchpadInputMapper.cpp.
53     switch (linuxBus) {
54         case BUS_USB:
55             return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__USB;
56         case BUS_BLUETOOTH:
57             return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__BLUETOOTH;
58         default:
59             return util::INPUT_DEVICE_USAGE_REPORTED__DEVICE_BUS__OTHER;
60     }
61 }
62 
63 class : public InputDeviceMetricsLogger {
getCurrentTime()64     nanoseconds getCurrentTime() override { return nanoseconds(systemTime(SYSTEM_TIME_MONOTONIC)); }
65 
logInputDeviceUsageReported(const MetricsDeviceInfo & info,const DeviceUsageReport & report)66     void logInputDeviceUsageReported(const MetricsDeviceInfo& info,
67                                      const DeviceUsageReport& report) override {
68         const int32_t durationMillis =
69                 std::chrono::duration_cast<std::chrono::milliseconds>(report.usageDuration).count();
70         const static std::vector<int32_t> empty;
71 
72         ALOGD_IF(DEBUG, "Usage session reported for device id: %d", info.deviceId);
73         ALOGD_IF(DEBUG, "    Total duration: %dms", durationMillis);
74         ALOGD_IF(DEBUG, "    Source breakdown:");
75 
76         std::vector<int32_t> sources;
77         std::vector<int32_t> durationsPerSource;
78         for (auto& [src, dur] : report.sourceBreakdown) {
79             sources.push_back(ftl::to_underlying(src));
80             int32_t durMillis = std::chrono::duration_cast<std::chrono::milliseconds>(dur).count();
81             durationsPerSource.emplace_back(durMillis);
82             ALOGD_IF(DEBUG, "        - usageSource: %s\t duration: %dms",
83                      ftl::enum_string(src).c_str(), durMillis);
84         }
85 
86         ALOGD_IF(DEBUG, "    Uid breakdown:");
87 
88         std::vector<int32_t> uids;
89         std::vector<int32_t> durationsPerUid;
90         for (auto& [uid, dur] : report.uidBreakdown) {
91             uids.push_back(uid.val());
92             int32_t durMillis = std::chrono::duration_cast<std::chrono::milliseconds>(dur).count();
93             durationsPerUid.push_back(durMillis);
94             ALOGD_IF(DEBUG, "        - uid: %s\t duration: %dms", uid.toString().c_str(),
95                      durMillis);
96         }
97         util::stats_write(util::INPUTDEVICE_USAGE_REPORTED, info.vendor, info.product, info.version,
98                           linuxBusToInputDeviceBusEnum(info.bus, info.isUsiStylus), durationMillis,
99                           sources, durationsPerSource, uids, durationsPerUid);
100     }
101 } sStatsdLogger;
102 
isIgnoredInputDeviceId(int32_t deviceId)103 bool isIgnoredInputDeviceId(int32_t deviceId) {
104     switch (deviceId) {
105         case INVALID_INPUT_DEVICE_ID:
106         case VIRTUAL_KEYBOARD_ID:
107             return true;
108         default:
109             return false;
110     }
111 }
112 
113 } // namespace
114 
InputDeviceMetricsCollector(InputListenerInterface & listener)115 InputDeviceMetricsCollector::InputDeviceMetricsCollector(InputListenerInterface& listener)
116       : InputDeviceMetricsCollector(listener, sStatsdLogger, DEFAULT_USAGE_SESSION_TIMEOUT) {}
117 
InputDeviceMetricsCollector(InputListenerInterface & listener,InputDeviceMetricsLogger & logger,nanoseconds usageSessionTimeout)118 InputDeviceMetricsCollector::InputDeviceMetricsCollector(InputListenerInterface& listener,
119                                                          InputDeviceMetricsLogger& logger,
120                                                          nanoseconds usageSessionTimeout)
121       : mNextListener(listener),
122         mLogger(logger),
123         mUsageSessionTimeout(usageSessionTimeout),
124         mInteractionsQueue(INTERACTIONS_QUEUE_CAPACITY) {}
125 
notifyInputDevicesChanged(const NotifyInputDevicesChangedArgs & args)126 void InputDeviceMetricsCollector::notifyInputDevicesChanged(
127         const NotifyInputDevicesChangedArgs& args) {
128     {
129         std::scoped_lock lock(mLock);
130         reportCompletedSessions();
131         onInputDevicesChanged(args.inputDeviceInfos);
132     }
133     mNextListener.notify(args);
134 }
135 
notifyKey(const NotifyKeyArgs & args)136 void InputDeviceMetricsCollector::notifyKey(const NotifyKeyArgs& args) {
137     {
138         std::scoped_lock lock(mLock);
139         reportCompletedSessions();
140         const SourceProvider getSources = [&args](const MetricsDeviceInfo& info) {
141             return std::set{getUsageSourceForKeyArgs(info.keyboardType, args)};
142         };
143         onInputDeviceUsage(DeviceId{args.deviceId}, nanoseconds(args.eventTime), getSources);
144     }
145     mNextListener.notify(args);
146 }
147 
notifyMotion(const NotifyMotionArgs & args)148 void InputDeviceMetricsCollector::notifyMotion(const NotifyMotionArgs& args) {
149     {
150         std::scoped_lock lock(mLock);
151         reportCompletedSessions();
152         onInputDeviceUsage(DeviceId{args.deviceId}, nanoseconds(args.eventTime),
153                            [&args](const auto&) { return getUsageSourcesForMotionArgs(args); });
154     }
155 
156     mNextListener.notify(args);
157 }
158 
notifySwitch(const NotifySwitchArgs & args)159 void InputDeviceMetricsCollector::notifySwitch(const NotifySwitchArgs& args) {
160     {
161         std::scoped_lock lock(mLock);
162         reportCompletedSessions();
163     }
164     mNextListener.notify(args);
165 }
166 
notifySensor(const NotifySensorArgs & args)167 void InputDeviceMetricsCollector::notifySensor(const NotifySensorArgs& args) {
168     {
169         std::scoped_lock lock(mLock);
170         reportCompletedSessions();
171     }
172     mNextListener.notify(args);
173 }
174 
notifyVibratorState(const NotifyVibratorStateArgs & args)175 void InputDeviceMetricsCollector::notifyVibratorState(const NotifyVibratorStateArgs& args) {
176     {
177         std::scoped_lock lock(mLock);
178         reportCompletedSessions();
179     }
180     mNextListener.notify(args);
181 }
182 
notifyDeviceReset(const NotifyDeviceResetArgs & args)183 void InputDeviceMetricsCollector::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
184     {
185         std::scoped_lock lock(mLock);
186         reportCompletedSessions();
187     }
188     mNextListener.notify(args);
189 }
190 
notifyPointerCaptureChanged(const NotifyPointerCaptureChangedArgs & args)191 void InputDeviceMetricsCollector::notifyPointerCaptureChanged(
192         const NotifyPointerCaptureChangedArgs& args) {
193     {
194         std::scoped_lock lock(mLock);
195         reportCompletedSessions();
196     }
197     mNextListener.notify(args);
198 }
199 
notifyDeviceInteraction(int32_t deviceId,nsecs_t timestamp,const std::set<Uid> & uids)200 void InputDeviceMetricsCollector::notifyDeviceInteraction(int32_t deviceId, nsecs_t timestamp,
201                                                           const std::set<Uid>& uids) {
202     if (isIgnoredInputDeviceId(deviceId)) {
203         return;
204     }
205     std::scoped_lock lock(mLock);
206     mInteractionsQueue.push(DeviceId{deviceId}, timestamp, uids);
207 }
208 
dump(std::string & dump)209 void InputDeviceMetricsCollector::dump(std::string& dump) {
210     std::scoped_lock lock(mLock);
211     dump += "InputDeviceMetricsCollector:\n";
212 
213     dump += "  Logged device IDs: " + dumpMapKeys(mLoggedDeviceInfos, &toString) + "\n";
214     dump += "  Devices with active usage sessions: " +
215             dumpMapKeys(mActiveUsageSessions, &toString) + "\n";
216 }
217 
monitor()218 void InputDeviceMetricsCollector::monitor() {
219     std::scoped_lock lock(mLock);
220 }
221 
onInputDevicesChanged(const std::vector<InputDeviceInfo> & infos)222 void InputDeviceMetricsCollector::onInputDevicesChanged(const std::vector<InputDeviceInfo>& infos) {
223     std::map<DeviceId, MetricsDeviceInfo> newDeviceInfos;
224 
225     for (const InputDeviceInfo& info : infos) {
226         if (isIgnoredInputDeviceId(info.getId())) {
227             continue;
228         }
229         const auto& i = info.getIdentifier();
230         newDeviceInfos.emplace(info.getId(),
231                                MetricsDeviceInfo{
232                                        .deviceId = info.getId(),
233                                        .vendor = i.vendor,
234                                        .product = i.product,
235                                        .version = i.version,
236                                        .bus = i.bus,
237                                        .isUsiStylus = info.getUsiVersion().has_value(),
238                                        .keyboardType = info.getKeyboardType(),
239                                });
240     }
241 
242     for (auto [deviceId, info] : mLoggedDeviceInfos) {
243         if (newDeviceInfos.count(deviceId) != 0) {
244             continue;
245         }
246         onInputDeviceRemoved(deviceId, info);
247     }
248 
249     std::swap(newDeviceInfos, mLoggedDeviceInfos);
250 }
251 
onInputDeviceRemoved(DeviceId deviceId,const MetricsDeviceInfo & info)252 void InputDeviceMetricsCollector::onInputDeviceRemoved(DeviceId deviceId,
253                                                        const MetricsDeviceInfo& info) {
254     auto it = mActiveUsageSessions.find(deviceId);
255     if (it == mActiveUsageSessions.end()) {
256         return;
257     }
258     // Report usage for that device if there is an active session.
259     auto& [_, activeSession] = *it;
260     mLogger.logInputDeviceUsageReported(info, activeSession.finishSession());
261     mActiveUsageSessions.erase(it);
262 
263     // We don't remove this from mLoggedDeviceInfos because it will be updated in
264     // onInputDevicesChanged().
265 }
266 
onInputDeviceUsage(DeviceId deviceId,nanoseconds eventTime,const SourceProvider & getSources)267 void InputDeviceMetricsCollector::onInputDeviceUsage(DeviceId deviceId, nanoseconds eventTime,
268                                                      const SourceProvider& getSources) {
269     auto infoIt = mLoggedDeviceInfos.find(deviceId);
270     if (infoIt == mLoggedDeviceInfos.end()) {
271         // Do not track usage for devices that are not logged.
272         return;
273     }
274 
275     auto [sessionIt, _] =
276             mActiveUsageSessions.try_emplace(deviceId, mUsageSessionTimeout, eventTime);
277     for (InputDeviceUsageSource source : getSources(infoIt->second)) {
278         sessionIt->second.recordUsage(eventTime, source);
279     }
280 }
281 
onInputDeviceInteraction(const Interaction & interaction)282 void InputDeviceMetricsCollector::onInputDeviceInteraction(const Interaction& interaction) {
283     auto activeSessionIt = mActiveUsageSessions.find(std::get<DeviceId>(interaction));
284     if (activeSessionIt == mActiveUsageSessions.end()) {
285         return;
286     }
287 
288     activeSessionIt->second.recordInteraction(interaction);
289 }
290 
reportCompletedSessions()291 void InputDeviceMetricsCollector::reportCompletedSessions() {
292     // Process all pending interactions.
293     for (auto interaction = mInteractionsQueue.pop(); interaction;
294          interaction = mInteractionsQueue.pop()) {
295         onInputDeviceInteraction(*interaction);
296     }
297 
298     const auto currentTime = mLogger.getCurrentTime();
299     std::vector<DeviceId> completedUsageSessions;
300 
301     // Process usages for all active session to determine if any sessions have expired.
302     for (auto& [deviceId, activeSession] : mActiveUsageSessions) {
303         if (activeSession.checkIfCompletedAt(currentTime)) {
304             completedUsageSessions.emplace_back(deviceId);
305         }
306     }
307 
308     // Close out and log all expired usage sessions.
309     for (DeviceId deviceId : completedUsageSessions) {
310         const auto infoIt = mLoggedDeviceInfos.find(deviceId);
311         LOG_ALWAYS_FATAL_IF(infoIt == mLoggedDeviceInfos.end());
312 
313         auto activeSessionIt = mActiveUsageSessions.find(deviceId);
314         LOG_ALWAYS_FATAL_IF(activeSessionIt == mActiveUsageSessions.end());
315         auto& [_, activeSession] = *activeSessionIt;
316         mLogger.logInputDeviceUsageReported(infoIt->second, activeSession.finishSession());
317         mActiveUsageSessions.erase(activeSessionIt);
318     }
319 }
320 
321 // --- InputDeviceMetricsCollector::ActiveSession ---
322 
ActiveSession(nanoseconds usageSessionTimeout,nanoseconds startTime)323 InputDeviceMetricsCollector::ActiveSession::ActiveSession(nanoseconds usageSessionTimeout,
324                                                           nanoseconds startTime)
325       : mUsageSessionTimeout(usageSessionTimeout), mDeviceSession({startTime, startTime}) {}
326 
recordUsage(nanoseconds eventTime,InputDeviceUsageSource source)327 void InputDeviceMetricsCollector::ActiveSession::recordUsage(nanoseconds eventTime,
328                                                              InputDeviceUsageSource source) {
329     // We assume that event times for subsequent events are always monotonically increasing for each
330     // input device.
331     auto [activeSourceIt, inserted] =
332             mActiveSessionsBySource.try_emplace(source, eventTime, eventTime);
333     if (!inserted) {
334         activeSourceIt->second.end = eventTime;
335     }
336     mDeviceSession.end = eventTime;
337 }
338 
recordInteraction(const Interaction & interaction)339 void InputDeviceMetricsCollector::ActiveSession::recordInteraction(const Interaction& interaction) {
340     const auto sessionExpiryTime = mDeviceSession.end + mUsageSessionTimeout;
341     const auto timestamp = std::get<nanoseconds>(interaction);
342     if (timestamp >= sessionExpiryTime) {
343         // This interaction occurred after the device's current active session is set to expire.
344         // Ignore it.
345         return;
346     }
347 
348     for (Uid uid : std::get<std::set<Uid>>(interaction)) {
349         auto [activeUidIt, inserted] = mActiveSessionsByUid.try_emplace(uid, timestamp, timestamp);
350         if (!inserted) {
351             activeUidIt->second.end = timestamp;
352         }
353     }
354 }
355 
checkIfCompletedAt(nanoseconds timestamp)356 bool InputDeviceMetricsCollector::ActiveSession::checkIfCompletedAt(nanoseconds timestamp) {
357     const auto sessionExpiryTime = timestamp - mUsageSessionTimeout;
358     std::vector<InputDeviceUsageSource> completedSourceSessionsForDevice;
359     for (auto& [source, session] : mActiveSessionsBySource) {
360         if (session.end <= sessionExpiryTime) {
361             completedSourceSessionsForDevice.emplace_back(source);
362         }
363     }
364     for (InputDeviceUsageSource source : completedSourceSessionsForDevice) {
365         auto it = mActiveSessionsBySource.find(source);
366         const auto& [_, session] = *it;
367         mSourceUsageBreakdown.emplace_back(source, session.end - session.start);
368         mActiveSessionsBySource.erase(it);
369     }
370 
371     std::vector<Uid> completedUidSessionsForDevice;
372     for (auto& [uid, session] : mActiveSessionsByUid) {
373         if (session.end <= sessionExpiryTime) {
374             completedUidSessionsForDevice.emplace_back(uid);
375         }
376     }
377     for (Uid uid : completedUidSessionsForDevice) {
378         auto it = mActiveSessionsByUid.find(uid);
379         const auto& [_, session] = *it;
380         mUidUsageBreakdown.emplace_back(uid, session.end - session.start);
381         mActiveSessionsByUid.erase(it);
382     }
383 
384     // This active session has expired if there are no more active source sessions tracked.
385     return mActiveSessionsBySource.empty();
386 }
387 
388 InputDeviceMetricsLogger::DeviceUsageReport
finishSession()389 InputDeviceMetricsCollector::ActiveSession::finishSession() {
390     const auto deviceUsageDuration = mDeviceSession.end - mDeviceSession.start;
391 
392     for (const auto& [source, sourceSession] : mActiveSessionsBySource) {
393         mSourceUsageBreakdown.emplace_back(source, sourceSession.end - sourceSession.start);
394     }
395     mActiveSessionsBySource.clear();
396 
397     for (const auto& [uid, uidSession] : mActiveSessionsByUid) {
398         mUidUsageBreakdown.emplace_back(uid, uidSession.end - uidSession.start);
399     }
400     mActiveSessionsByUid.clear();
401 
402     return {deviceUsageDuration, mSourceUsageBreakdown, mUidUsageBreakdown};
403 }
404 
405 } // namespace android
406