blob: 46211441a9446c100732577c6872be0b1787da6d [file] [log] [blame]
Prabir Pradhanaddf8e92023-04-06 00:28:48 +00001/*
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
Asmita Poddar631a14e2023-10-03 10:22:07 +000020#include "InputDeviceMetricsSource.h"
Prabir Pradhanae10ee62023-05-12 19:44:18 +000021
Prabir Pradhan852db892023-04-06 22:16:44 +000022#include <android-base/stringprintf.h>
23#include <input/PrintTools.h>
Prabir Pradhan852db892023-04-06 22:16:44 +000024
Prabir Pradhanaddf8e92023-04-06 00:28:48 +000025namespace android {
26
Prabir Pradhan852db892023-04-06 22:16:44 +000027using android::base::StringPrintf;
28using std::chrono::nanoseconds;
Prabir Pradhan44293792023-05-08 19:37:44 +000029using std::chrono_literals::operator""ns;
Prabir Pradhan852db892023-04-06 22:16:44 +000030
31namespace {
32
Prabir Pradhan7adabad2023-06-28 16:16:27 +000033constexpr nanoseconds DEFAULT_USAGE_SESSION_TIMEOUT = std::chrono::minutes(2);
Prabir Pradhan852db892023-04-06 22:16:44 +000034
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 */
39const bool DEBUG = __android_log_is_loggable(ANDROID_LOG_DEBUG, LOG_TAG, ANDROID_LOG_INFO);
40
Prabir Pradhan047695b2023-06-30 01:48:45 +000041constexpr size_t INTERACTIONS_QUEUE_CAPACITY = 500;
42
Prabir Pradhan67d09ca2023-09-08 20:28:55 +000043int32_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
Harry Cuttsa34de522023-06-06 15:52:54 +000050 // 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.
Prabir Pradhan852db892023-04-06 22:16:44 +000053 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
63class : public InputDeviceMetricsLogger {
64 nanoseconds getCurrentTime() override { return nanoseconds(systemTime(SYSTEM_TIME_MONOTONIC)); }
65
Prabir Pradhan0dd48ae2023-09-08 21:33:51 +000066 void logInputDeviceUsageReported(const MetricsDeviceInfo& info,
Prabir Pradhanaff13032023-04-07 22:25:03 +000067 const DeviceUsageReport& report) override {
Prabir Pradhan852db892023-04-06 22:16:44 +000068 const int32_t durationMillis =
Prabir Pradhanaff13032023-04-07 22:25:03 +000069 std::chrono::duration_cast<std::chrono::milliseconds>(report.usageDuration).count();
Prabir Pradhan852db892023-04-06 22:16:44 +000070 const static std::vector<int32_t> empty;
71
Prabir Pradhan0dd48ae2023-09-08 21:33:51 +000072 ALOGD_IF(DEBUG, "Usage session reported for device id: %d", info.deviceId);
Prabir Pradhan852db892023-04-06 22:16:44 +000073 ALOGD_IF(DEBUG, " Total duration: %dms", durationMillis);
Prabir Pradhanaff13032023-04-07 22:25:03 +000074 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 }
Prabir Pradhan852db892023-04-06 22:16:44 +000085
Prabir Pradhan44293792023-05-08 19:37:44 +000086 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) {
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +000091 uids.push_back(uid.val());
Prabir Pradhan44293792023-05-08 19:37:44 +000092 int32_t durMillis = std::chrono::duration_cast<std::chrono::milliseconds>(dur).count();
93 durationsPerUid.push_back(durMillis);
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +000094 ALOGD_IF(DEBUG, " - uid: %s\t duration: %dms", uid.toString().c_str(),
95 durMillis);
Prabir Pradhan44293792023-05-08 19:37:44 +000096 }
Prabir Pradhan0dd48ae2023-09-08 21:33:51 +000097 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);
Prabir Pradhan852db892023-04-06 22:16:44 +0000100 }
101} sStatsdLogger;
102
103bool 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
Prabir Pradhanaddf8e92023-04-06 00:28:48 +0000115InputDeviceMetricsCollector::InputDeviceMetricsCollector(InputListenerInterface& listener)
Prabir Pradhan852db892023-04-06 22:16:44 +0000116 : InputDeviceMetricsCollector(listener, sStatsdLogger, DEFAULT_USAGE_SESSION_TIMEOUT) {}
117
118InputDeviceMetricsCollector::InputDeviceMetricsCollector(InputListenerInterface& listener,
119 InputDeviceMetricsLogger& logger,
120 nanoseconds usageSessionTimeout)
Prabir Pradhan047695b2023-06-30 01:48:45 +0000121 : mNextListener(listener),
122 mLogger(logger),
123 mUsageSessionTimeout(usageSessionTimeout),
124 mInteractionsQueue(INTERACTIONS_QUEUE_CAPACITY) {}
Prabir Pradhanaddf8e92023-04-06 00:28:48 +0000125
126void InputDeviceMetricsCollector::notifyInputDevicesChanged(
127 const NotifyInputDevicesChangedArgs& args) {
Prabir Pradhan95019ac2023-12-06 22:38:21 +0000128 {
129 std::scoped_lock lock(mLock);
130 reportCompletedSessions();
131 onInputDevicesChanged(args.inputDeviceInfos);
132 }
Prabir Pradhanaddf8e92023-04-06 00:28:48 +0000133 mNextListener.notify(args);
134}
135
Prabir Pradhanaddf8e92023-04-06 00:28:48 +0000136void InputDeviceMetricsCollector::notifyKey(const NotifyKeyArgs& args) {
Prabir Pradhan95019ac2023-12-06 22:38:21 +0000137 {
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 }
Prabir Pradhanaddf8e92023-04-06 00:28:48 +0000145 mNextListener.notify(args);
146}
147
148void InputDeviceMetricsCollector::notifyMotion(const NotifyMotionArgs& args) {
Prabir Pradhan95019ac2023-12-06 22:38:21 +0000149 {
150 std::scoped_lock lock(mLock);
151 reportCompletedSessions();
152 onInputDeviceUsage(DeviceId{args.deviceId}, nanoseconds(args.eventTime),
153 [&args](const auto&) { return getUsageSourcesForMotionArgs(args); });
154 }
Prabir Pradhan852db892023-04-06 22:16:44 +0000155
Prabir Pradhanaddf8e92023-04-06 00:28:48 +0000156 mNextListener.notify(args);
157}
158
159void InputDeviceMetricsCollector::notifySwitch(const NotifySwitchArgs& args) {
Prabir Pradhan95019ac2023-12-06 22:38:21 +0000160 {
161 std::scoped_lock lock(mLock);
162 reportCompletedSessions();
163 }
Prabir Pradhanaddf8e92023-04-06 00:28:48 +0000164 mNextListener.notify(args);
165}
166
167void InputDeviceMetricsCollector::notifySensor(const NotifySensorArgs& args) {
Prabir Pradhan95019ac2023-12-06 22:38:21 +0000168 {
169 std::scoped_lock lock(mLock);
170 reportCompletedSessions();
171 }
Prabir Pradhanaddf8e92023-04-06 00:28:48 +0000172 mNextListener.notify(args);
173}
174
175void InputDeviceMetricsCollector::notifyVibratorState(const NotifyVibratorStateArgs& args) {
Prabir Pradhan95019ac2023-12-06 22:38:21 +0000176 {
177 std::scoped_lock lock(mLock);
178 reportCompletedSessions();
179 }
Prabir Pradhanaddf8e92023-04-06 00:28:48 +0000180 mNextListener.notify(args);
181}
182
183void InputDeviceMetricsCollector::notifyDeviceReset(const NotifyDeviceResetArgs& args) {
Prabir Pradhan95019ac2023-12-06 22:38:21 +0000184 {
185 std::scoped_lock lock(mLock);
186 reportCompletedSessions();
187 }
Prabir Pradhanaddf8e92023-04-06 00:28:48 +0000188 mNextListener.notify(args);
189}
190
191void InputDeviceMetricsCollector::notifyPointerCaptureChanged(
192 const NotifyPointerCaptureChangedArgs& args) {
Prabir Pradhan95019ac2023-12-06 22:38:21 +0000193 {
194 std::scoped_lock lock(mLock);
195 reportCompletedSessions();
196 }
Prabir Pradhanaddf8e92023-04-06 00:28:48 +0000197 mNextListener.notify(args);
198}
199
Prabir Pradhan8ede1d12023-05-08 19:37:44 +0000200void InputDeviceMetricsCollector::notifyDeviceInteraction(int32_t deviceId, nsecs_t timestamp,
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000201 const std::set<Uid>& uids) {
Prabir Pradhan047695b2023-06-30 01:48:45 +0000202 if (isIgnoredInputDeviceId(deviceId)) {
203 return;
204 }
Prabir Pradhan95019ac2023-12-06 22:38:21 +0000205 std::scoped_lock lock(mLock);
Prabir Pradhan8a5c41d2023-06-08 19:13:46 +0000206 mInteractionsQueue.push(DeviceId{deviceId}, timestamp, uids);
Prabir Pradhan8ede1d12023-05-08 19:37:44 +0000207}
208
Prabir Pradhanaddf8e92023-04-06 00:28:48 +0000209void InputDeviceMetricsCollector::dump(std::string& dump) {
Prabir Pradhan95019ac2023-12-06 22:38:21 +0000210 std::scoped_lock lock(mLock);
Prabir Pradhanaddf8e92023-04-06 00:28:48 +0000211 dump += "InputDeviceMetricsCollector:\n";
Prabir Pradhan852db892023-04-06 22:16:44 +0000212
213 dump += " Logged device IDs: " + dumpMapKeys(mLoggedDeviceInfos, &toString) + "\n";
214 dump += " Devices with active usage sessions: " +
215 dumpMapKeys(mActiveUsageSessions, &toString) + "\n";
216}
217
Prabir Pradhan95019ac2023-12-06 22:38:21 +0000218void InputDeviceMetricsCollector::monitor() {
219 std::scoped_lock lock(mLock);
220}
221
Prabir Pradhan852db892023-04-06 22:16:44 +0000222void InputDeviceMetricsCollector::onInputDevicesChanged(const std::vector<InputDeviceInfo>& infos) {
Prabir Pradhan0dd48ae2023-09-08 21:33:51 +0000223 std::map<DeviceId, MetricsDeviceInfo> newDeviceInfos;
Prabir Pradhan852db892023-04-06 22:16:44 +0000224
225 for (const InputDeviceInfo& info : infos) {
226 if (isIgnoredInputDeviceId(info.getId())) {
227 continue;
228 }
Prabir Pradhan0dd48ae2023-09-08 21:33:51 +0000229 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 });
Prabir Pradhan852db892023-04-06 22:16:44 +0000240 }
241
Prabir Pradhanaff13032023-04-07 22:25:03 +0000242 for (auto [deviceId, info] : mLoggedDeviceInfos) {
243 if (newDeviceInfos.count(deviceId) != 0) {
Prabir Pradhan852db892023-04-06 22:16:44 +0000244 continue;
245 }
Prabir Pradhan67d09ca2023-09-08 20:28:55 +0000246 onInputDeviceRemoved(deviceId, info);
Prabir Pradhan852db892023-04-06 22:16:44 +0000247 }
248
Prabir Pradhanaff13032023-04-07 22:25:03 +0000249 std::swap(newDeviceInfos, mLoggedDeviceInfos);
Prabir Pradhan852db892023-04-06 22:16:44 +0000250}
251
252void InputDeviceMetricsCollector::onInputDeviceRemoved(DeviceId deviceId,
Prabir Pradhan0dd48ae2023-09-08 21:33:51 +0000253 const MetricsDeviceInfo& info) {
Prabir Pradhan852db892023-04-06 22:16:44 +0000254 auto it = mActiveUsageSessions.find(deviceId);
Prabir Pradhanaff13032023-04-07 22:25:03 +0000255 if (it == mActiveUsageSessions.end()) {
256 return;
Prabir Pradhan852db892023-04-06 22:16:44 +0000257 }
Prabir Pradhanaff13032023-04-07 22:25:03 +0000258 // Report usage for that device if there is an active session.
259 auto& [_, activeSession] = *it;
Prabir Pradhan67d09ca2023-09-08 20:28:55 +0000260 mLogger.logInputDeviceUsageReported(info, activeSession.finishSession());
Prabir Pradhanaff13032023-04-07 22:25:03 +0000261 mActiveUsageSessions.erase(it);
262
Prabir Pradhan852db892023-04-06 22:16:44 +0000263 // We don't remove this from mLoggedDeviceInfos because it will be updated in
264 // onInputDevicesChanged().
265}
266
Prabir Pradhanaff13032023-04-07 22:25:03 +0000267void InputDeviceMetricsCollector::onInputDeviceUsage(DeviceId deviceId, nanoseconds eventTime,
268 const SourceProvider& getSources) {
269 auto infoIt = mLoggedDeviceInfos.find(deviceId);
270 if (infoIt == mLoggedDeviceInfos.end()) {
Prabir Pradhan852db892023-04-06 22:16:44 +0000271 // Do not track usage for devices that are not logged.
272 return;
273 }
274
Prabir Pradhanaff13032023-04-07 22:25:03 +0000275 auto [sessionIt, _] =
276 mActiveUsageSessions.try_emplace(deviceId, mUsageSessionTimeout, eventTime);
277 for (InputDeviceUsageSource source : getSources(infoIt->second)) {
278 sessionIt->second.recordUsage(eventTime, source);
Prabir Pradhan852db892023-04-06 22:16:44 +0000279 }
280}
281
Prabir Pradhan44293792023-05-08 19:37:44 +0000282void InputDeviceMetricsCollector::onInputDeviceInteraction(const Interaction& interaction) {
283 auto activeSessionIt = mActiveUsageSessions.find(std::get<DeviceId>(interaction));
284 if (activeSessionIt == mActiveUsageSessions.end()) {
285 return;
286 }
Prabir Pradhan852db892023-04-06 22:16:44 +0000287
Prabir Pradhan44293792023-05-08 19:37:44 +0000288 activeSessionIt->second.recordInteraction(interaction);
289}
290
291void 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();
Prabir Pradhan852db892023-04-06 22:16:44 +0000299 std::vector<DeviceId> completedUsageSessions;
300
Prabir Pradhan44293792023-05-08 19:37:44 +0000301 // Process usages for all active session to determine if any sessions have expired.
Prabir Pradhanaff13032023-04-07 22:25:03 +0000302 for (auto& [deviceId, activeSession] : mActiveUsageSessions) {
303 if (activeSession.checkIfCompletedAt(currentTime)) {
Prabir Pradhan852db892023-04-06 22:16:44 +0000304 completedUsageSessions.emplace_back(deviceId);
305 }
306 }
307
Prabir Pradhan44293792023-05-08 19:37:44 +0000308 // Close out and log all expired usage sessions.
Prabir Pradhan852db892023-04-06 22:16:44 +0000309 for (DeviceId deviceId : completedUsageSessions) {
Prabir Pradhanaff13032023-04-07 22:25:03 +0000310 const auto infoIt = mLoggedDeviceInfos.find(deviceId);
311 LOG_ALWAYS_FATAL_IF(infoIt == mLoggedDeviceInfos.end());
Prabir Pradhan852db892023-04-06 22:16:44 +0000312
Prabir Pradhanaff13032023-04-07 22:25:03 +0000313 auto activeSessionIt = mActiveUsageSessions.find(deviceId);
314 LOG_ALWAYS_FATAL_IF(activeSessionIt == mActiveUsageSessions.end());
315 auto& [_, activeSession] = *activeSessionIt;
Prabir Pradhan67d09ca2023-09-08 20:28:55 +0000316 mLogger.logInputDeviceUsageReported(infoIt->second, activeSession.finishSession());
Prabir Pradhanaff13032023-04-07 22:25:03 +0000317 mActiveUsageSessions.erase(activeSessionIt);
Prabir Pradhan852db892023-04-06 22:16:44 +0000318 }
Prabir Pradhanaddf8e92023-04-06 00:28:48 +0000319}
320
Prabir Pradhanaff13032023-04-07 22:25:03 +0000321// --- InputDeviceMetricsCollector::ActiveSession ---
322
323InputDeviceMetricsCollector::ActiveSession::ActiveSession(nanoseconds usageSessionTimeout,
324 nanoseconds startTime)
325 : mUsageSessionTimeout(usageSessionTimeout), mDeviceSession({startTime, startTime}) {}
326
327void 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
Prabir Pradhan44293792023-05-08 19:37:44 +0000339void 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
Prabir Pradhanaff13032023-04-07 22:25:03 +0000356bool 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 }
Prabir Pradhan44293792023-05-08 19:37:44 +0000370
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.
Prabir Pradhanaff13032023-04-07 22:25:03 +0000385 return mActiveSessionsBySource.empty();
386}
387
388InputDeviceMetricsLogger::DeviceUsageReport
389InputDeviceMetricsCollector::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
Prabir Pradhan44293792023-05-08 19:37:44 +0000397 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};
Prabir Pradhanaff13032023-04-07 22:25:03 +0000403}
404
Prabir Pradhanaddf8e92023-04-06 00:28:48 +0000405} // namespace android