blob: 1309626eee7094f3cbdabf3ca78b58da1da089c6 [file] [log] [blame]
Ray Essick3938dc62016-11-01 08:56:56 -07001/*
Ray Essick2e9c63b2017-03-29 15:16:44 -07002 * Copyright (C) 2017 The Android Open Source Project
Ray Essick3938dc62016-11-01 08:56:56 -07003 *
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
Ray Essick3938dc62016-11-01 08:56:56 -070017//#define LOG_NDEBUG 0
Ray Essickf27e9872019-12-07 06:28:46 -080018#define LOG_TAG "MediaMetricsService"
Ray Essick3938dc62016-11-01 08:56:56 -070019#include <utils/Log.h>
20
Ray Essick40e8e5e2019-12-05 20:19:40 -080021#include "MediaMetricsService.h"
Andy Hungc9b6f8b2021-07-08 10:17:55 -070022#include "ValidateId.h"
Robert Shih2e15aed2021-03-16 18:30:35 -070023#include "iface_statsd.h"
Ray Essick3938dc62016-11-01 08:56:56 -070024
Andy Hung17dbaf22019-10-11 14:06:31 -070025#include <pwd.h> //getpwuid
26
Andy Hung54c73ce2021-03-30 14:25:54 -070027#include <android-base/stringprintf.h>
Andy Hung17dbaf22019-10-11 14:06:31 -070028#include <android/content/pm/IPackageManagerNative.h> // package info
Andy Hung55aaf522019-12-03 15:07:51 -080029#include <audio_utils/clock.h> // clock conversions
Andy Hung17dbaf22019-10-11 14:06:31 -070030#include <binder/IPCThreadState.h> // get calling uid
Andy Hung49ca44e2020-11-10 22:14:58 -080031#include <binder/IServiceManager.h> // checkCallingPermission
Andy Hung17dbaf22019-10-11 14:06:31 -070032#include <cutils/properties.h> // for property_get
Andy Hung9099a1a2020-04-04 14:23:36 -070033#include <mediautils/MemoryLeakTrackUtil.h>
34#include <memunreachable/memunreachable.h>
Andy Hung17dbaf22019-10-11 14:06:31 -070035#include <private/android_filesystem_config.h> // UID
Vova Sharaienkof58455a2022-09-24 01:47:23 +000036#include <stats_media_metrics.h>
Robert Shih2e15aed2021-03-16 18:30:35 -070037
38#include <set>
Andy Hung17dbaf22019-10-11 14:06:31 -070039
Ray Essick3938dc62016-11-01 08:56:56 -070040namespace android {
41
Andy Hung54c73ce2021-03-30 14:25:54 -070042using base::StringPrintf;
Andy Hung3ab1b322020-05-18 10:47:31 -070043using mediametrics::Item;
44using mediametrics::startsWith;
Andy Hung1efc9c62019-12-03 13:43:33 -080045
Ray Essickf65f4212017-08-31 11:41:19 -070046// individual records kept in memory: age or count
Ray Essick72a436b2018-06-14 15:08:13 -070047// age: <= 28 hours (1 1/6 days)
Ray Essickf65f4212017-08-31 11:41:19 -070048// count: hard limit of # records
49// (0 for either of these disables that threshold)
Ray Essick72a436b2018-06-14 15:08:13 -070050//
Andy Hung17dbaf22019-10-11 14:06:31 -070051static constexpr nsecs_t kMaxRecordAgeNs = 28 * 3600 * NANOS_PER_SECOND;
Ray Essick23f4d6c2019-06-20 10:16:37 -070052// 2019/6: average daily per device is currently 375-ish;
53// setting this to 2000 is large enough to catch most devices
54// we'll lose some data on very very media-active devices, but only for
55// the gms collection; statsd will have already covered those for us.
56// This also retains enough information to help with bugreports
Andy Hung17dbaf22019-10-11 14:06:31 -070057static constexpr size_t kMaxRecords = 2000;
Ray Essick72a436b2018-06-14 15:08:13 -070058
59// max we expire in a single call, to constrain how long we hold the
60// mutex, which also constrains how long a client might wait.
Andy Hung17dbaf22019-10-11 14:06:31 -070061static constexpr size_t kMaxExpiredAtOnce = 50;
Ray Essick72a436b2018-06-14 15:08:13 -070062
63// TODO: need to look at tuning kMaxRecords and friends for low-memory devices
Ray Essick2e9c63b2017-03-29 15:16:44 -070064
Andy Hung55aaf522019-12-03 15:07:51 -080065/* static */
Ray Essickf27e9872019-12-07 06:28:46 -080066nsecs_t MediaMetricsService::roundTime(nsecs_t timeNs)
Andy Hung55aaf522019-12-03 15:07:51 -080067{
68 return (timeNs + NANOS_PER_SECOND / 2) / NANOS_PER_SECOND * NANOS_PER_SECOND;
69}
70
Andy Hunga85efab2019-12-23 11:41:29 -080071/* static */
72bool MediaMetricsService::useUidForPackage(
73 const std::string& package, const std::string& installer)
74{
Chih-Hung Hsiehac521522022-06-09 23:16:12 -070075 // NOLINTBEGIN(bugprone-branch-clone)
Andy Hung3ab1b322020-05-18 10:47:31 -070076 if (strchr(package.c_str(), '.') == nullptr) {
Andy Hunga85efab2019-12-23 11:41:29 -080077 return false; // not of form 'com.whatever...'; assume internal and ok
78 } else if (strncmp(package.c_str(), "android.", 8) == 0) {
79 return false; // android.* packages are assumed fine
80 } else if (strncmp(installer.c_str(), "com.android.", 12) == 0) {
81 return false; // from play store
82 } else if (strncmp(installer.c_str(), "com.google.", 11) == 0) {
83 return false; // some google source
84 } else if (strcmp(installer.c_str(), "preload") == 0) {
85 return false; // preloads
86 } else {
87 return true; // we're not sure where it came from, use uid only.
88 }
Chih-Hung Hsiehac521522022-06-09 23:16:12 -070089 // NOLINTEND(bugprone-branch-clone)
Andy Hunga85efab2019-12-23 11:41:29 -080090}
91
Andy Hungce9b6632020-04-28 20:15:17 -070092/* static */
93std::pair<std::string, int64_t>
94MediaMetricsService::getSanitizedPackageNameAndVersionCode(uid_t uid) {
Andy Hungb26a1c82024-08-30 11:54:40 -070095 const std::shared_ptr<const mediautils::UidInfo::Info> info =
96 mediautils::UidInfo::getInfo(uid);
97 if (useUidForPackage(info->package, info->installer)) {
Andy Hungce9b6632020-04-28 20:15:17 -070098 return { std::to_string(uid), /* versionCode */ 0 };
99 } else {
Andy Hungb26a1c82024-08-30 11:54:40 -0700100 return { info->package, info->versionCode };
Andy Hungce9b6632020-04-28 20:15:17 -0700101 }
102}
103
Ray Essickf27e9872019-12-07 06:28:46 -0800104MediaMetricsService::MediaMetricsService()
Ray Essick2e9c63b2017-03-29 15:16:44 -0700105 : mMaxRecords(kMaxRecords),
Ray Essickf65f4212017-08-31 11:41:19 -0700106 mMaxRecordAgeNs(kMaxRecordAgeNs),
Andy Hung3b4c1f02020-01-23 18:58:32 -0800107 mMaxRecordsExpiredAtOnce(kMaxExpiredAtOnce)
Andy Hung17dbaf22019-10-11 14:06:31 -0700108{
109 ALOGD("%s", __func__);
Ray Essick3938dc62016-11-01 08:56:56 -0700110}
111
Ray Essickf27e9872019-12-07 06:28:46 -0800112MediaMetricsService::~MediaMetricsService()
Andy Hung17dbaf22019-10-11 14:06:31 -0700113{
114 ALOGD("%s", __func__);
115 // the class destructor clears anyhow, but we enforce clearing items first.
Andy Hungc14ee142021-03-10 16:39:02 -0800116 mItemsDiscarded += (int64_t)mItems.size();
Andy Hung17dbaf22019-10-11 14:06:31 -0700117 mItems.clear();
Ray Essick3938dc62016-11-01 08:56:56 -0700118}
119
Ray Essickf27e9872019-12-07 06:28:46 -0800120status_t MediaMetricsService::submitInternal(mediametrics::Item *item, bool release)
Ray Essick92d23b42018-01-29 12:10:30 -0800121{
Andy Hung55aaf522019-12-03 15:07:51 -0800122 // calling PID is 0 for one-way calls.
123 const pid_t pid = IPCThreadState::self()->getCallingPid();
124 const pid_t pid_given = item->getPid();
125 const uid_t uid = IPCThreadState::self()->getCallingUid();
126 const uid_t uid_given = item->getUid();
Ray Essickd38e1742017-01-23 15:17:06 -0800127
Andy Hung55aaf522019-12-03 15:07:51 -0800128 //ALOGD("%s: caller pid=%d uid=%d, item pid=%d uid=%d", __func__,
129 // (int)pid, (int)uid, (int) pid_given, (int)uid_given);
Ray Essickd38e1742017-01-23 15:17:06 -0800130
Andy Hung17dbaf22019-10-11 14:06:31 -0700131 bool isTrusted;
132 switch (uid) {
Andy Hung55aaf522019-12-03 15:07:51 -0800133 case AID_AUDIOSERVER:
134 case AID_BLUETOOTH:
135 case AID_CAMERA:
Andy Hung17dbaf22019-10-11 14:06:31 -0700136 case AID_DRM:
137 case AID_MEDIA:
138 case AID_MEDIA_CODEC:
139 case AID_MEDIA_EX:
140 case AID_MEDIA_DRM:
Andy Hung5d3f2d12020-03-04 19:55:03 -0800141 // case AID_SHELL: // DEBUG ONLY - used for mediametrics_tests to add new keys
Andy Hung55aaf522019-12-03 15:07:51 -0800142 case AID_SYSTEM:
Andy Hung17dbaf22019-10-11 14:06:31 -0700143 // trusted source, only override default values
144 isTrusted = true;
Andy Hung55aaf522019-12-03 15:07:51 -0800145 if (uid_given == (uid_t)-1) {
Ray Essickd38e1742017-01-23 15:17:06 -0800146 item->setUid(uid);
Andy Hung17dbaf22019-10-11 14:06:31 -0700147 }
Andy Hung55aaf522019-12-03 15:07:51 -0800148 if (pid_given == (pid_t)-1) {
149 item->setPid(pid); // if one-way then this is 0.
Andy Hung17dbaf22019-10-11 14:06:31 -0700150 }
151 break;
152 default:
153 isTrusted = false;
Andy Hung55aaf522019-12-03 15:07:51 -0800154 item->setPid(pid); // always use calling pid, if one-way then this is 0.
Andy Hung17dbaf22019-10-11 14:06:31 -0700155 item->setUid(uid);
156 break;
Ray Essickd38e1742017-01-23 15:17:06 -0800157 }
158
Andy Hunga85efab2019-12-23 11:41:29 -0800159 // Overwrite package name and version if the caller was untrusted or empty
160 if (!isTrusted || item->getPkgName().empty()) {
Andy Hung3ab1b322020-05-18 10:47:31 -0700161 const uid_t uidItem = item->getUid();
Andy Hungce9b6632020-04-28 20:15:17 -0700162 const auto [ pkgName, version ] =
Andy Hung3ab1b322020-05-18 10:47:31 -0700163 MediaMetricsService::getSanitizedPackageNameAndVersionCode(uidItem);
Andy Hungce9b6632020-04-28 20:15:17 -0700164 item->setPkgName(pkgName);
165 item->setPkgVersionCode(version);
Adam Stone21c72122017-09-05 19:02:06 -0700166 }
167
Andy Hung5d3f2d12020-03-04 19:55:03 -0800168 ALOGV("%s: isTrusted:%d given uid %d; sanitized uid: %d sanitized pkg: %s "
Andy Hung17dbaf22019-10-11 14:06:31 -0700169 "sanitized pkg version: %lld",
170 __func__,
Andy Hung5d3f2d12020-03-04 19:55:03 -0800171 (int)isTrusted,
Adam Stone21c72122017-09-05 19:02:06 -0700172 uid_given, item->getUid(),
173 item->getPkgName().c_str(),
Andy Hung17dbaf22019-10-11 14:06:31 -0700174 (long long)item->getPkgVersionCode());
Ray Essick3938dc62016-11-01 08:56:56 -0700175
176 mItemsSubmitted++;
177
178 // validate the record; we discard if we don't like it
Andy Hung17dbaf22019-10-11 14:06:31 -0700179 if (isContentValid(item, isTrusted) == false) {
Andy Hunga87e69c2019-10-18 10:07:40 -0700180 if (release) delete item;
181 return PERMISSION_DENIED;
Ray Essick3938dc62016-11-01 08:56:56 -0700182 }
183
Ray Essick92d23b42018-01-29 12:10:30 -0800184 // XXX: if we have a sessionid in the new record, look to make
Ray Essick3938dc62016-11-01 08:56:56 -0700185 // sure it doesn't appear in the finalized list.
Ray Essick3938dc62016-11-01 08:56:56 -0700186
Ray Essick92d23b42018-01-29 12:10:30 -0800187 if (item->count() == 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700188 ALOGV("%s: dropping empty record...", __func__);
Andy Hunga87e69c2019-10-18 10:07:40 -0700189 if (release) delete item;
190 return BAD_VALUE;
Ray Essick3938dc62016-11-01 08:56:56 -0700191 }
Ray Essick92d23b42018-01-29 12:10:30 -0800192
Andy Hung55aaf522019-12-03 15:07:51 -0800193 if (!isTrusted || item->getTimestamp() == 0) {
Muhammad Qureshi087b37c2020-06-16 16:37:36 -0700194 // Statsd logs two times for events: ElapsedRealTimeNs (BOOTTIME) and
Andy Hung3b4c1f02020-01-23 18:58:32 -0800195 // WallClockTimeNs (REALTIME), but currently logs REALTIME to cloud.
Andy Hung55aaf522019-12-03 15:07:51 -0800196 //
Andy Hung3b4c1f02020-01-23 18:58:32 -0800197 // For consistency and correlation with other logging mechanisms
198 // we use REALTIME here.
199 const int64_t now = systemTime(SYSTEM_TIME_REALTIME);
Andy Hung55aaf522019-12-03 15:07:51 -0800200 item->setTimestamp(now);
201 }
202
Andy Hung82a074b2019-12-03 14:16:45 -0800203 // now attach either the item or its dup to a const shared pointer
Ray Essickf27e9872019-12-07 06:28:46 -0800204 std::shared_ptr<const mediametrics::Item> sitem(release ? item : item->dup());
Ray Essick6ce27e52019-02-15 10:58:05 -0800205
Andy Hungc9b6f8b2021-07-08 10:17:55 -0700206 // register log session ids with singleton.
207 if (startsWith(item->getKey(), "metrics.manager")) {
208 std::string logSessionId;
209 if (item->get("logSessionId", &logSessionId)
210 && mediametrics::stringutils::isLogSessionId(logSessionId.c_str())) {
211 mediametrics::ValidateId::get()->registerId(logSessionId);
212 }
213 }
214
Andy Hung06f3aba2019-12-03 16:36:42 -0800215 (void)mAudioAnalytics.submit(sitem, isTrusted);
216
Andy Hung5be90c82021-03-30 14:30:20 -0700217 (void)dump2Statsd(sitem, mStatsdLog); // failure should be logged in function.
Andy Hung82a074b2019-12-03 14:16:45 -0800218 saveItem(sitem);
Andy Hunga87e69c2019-10-18 10:07:40 -0700219 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700220}
221
Ray Essickf27e9872019-12-07 06:28:46 -0800222status_t MediaMetricsService::dump(int fd, const Vector<String16>& args)
Ray Essick3938dc62016-11-01 08:56:56 -0700223{
Ray Essick3938dc62016-11-01 08:56:56 -0700224 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700225 const std::string result = StringPrintf("Permission Denial: "
Ray Essickf27e9872019-12-07 06:28:46 -0800226 "can't dump MediaMetricsService from pid=%d, uid=%d\n",
Ray Essick3938dc62016-11-01 08:56:56 -0700227 IPCThreadState::self()->getCallingPid(),
228 IPCThreadState::self()->getCallingUid());
Andy Hung54c73ce2021-03-30 14:25:54 -0700229 write(fd, result.c_str(), result.size());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800230 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700231 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800232
Andy Hung709b91e2020-04-04 14:23:36 -0700233 static const String16 allOption("--all");
234 static const String16 clearOption("--clear");
Andy Hung9099a1a2020-04-04 14:23:36 -0700235 static const String16 heapOption("--heap");
Andy Hung709b91e2020-04-04 14:23:36 -0700236 static const String16 helpOption("--help");
237 static const String16 prefixOption("--prefix");
238 static const String16 sinceOption("--since");
Andy Hung9099a1a2020-04-04 14:23:36 -0700239 static const String16 unreachableOption("--unreachable");
Andy Hung709b91e2020-04-04 14:23:36 -0700240
241 bool all = false;
242 bool clear = false;
Andy Hung9099a1a2020-04-04 14:23:36 -0700243 bool heap = false;
244 bool unreachable = false;
Andy Hung709b91e2020-04-04 14:23:36 -0700245 int64_t sinceNs = 0;
246 std::string prefix;
Andy Hung9099a1a2020-04-04 14:23:36 -0700247
Andy Hung709b91e2020-04-04 14:23:36 -0700248 const size_t n = args.size();
249 for (size_t i = 0; i < n; i++) {
250 if (args[i] == allOption) {
251 all = true;
252 } else if (args[i] == clearOption) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800253 clear = true;
Andy Hung9099a1a2020-04-04 14:23:36 -0700254 } else if (args[i] == heapOption) {
255 heap = true;
Ray Essick35ad27f2017-01-30 14:04:11 -0800256 } else if (args[i] == helpOption) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700257 // TODO: consider function area dumping.
258 // dumpsys media.metrics audiotrack,codec
259 // or dumpsys media.metrics audiotrack codec
260
Andy Hung54c73ce2021-03-30 14:25:54 -0700261 static constexpr char result[] =
262 "Recognized parameters:\n"
263 "--all show all records\n"
264 "--clear clear out saved records\n"
265 "--heap show heap usage (top 100)\n"
266 "--help display help\n"
267 "--prefix X process records for component X\n"
268 "--since X X < 0: records from -X seconds in the past\n"
269 " X = 0: ignore\n"
270 " X > 0: records from X seconds since Unix epoch\n"
271 "--unreachable show unreachable memory (leaks)\n";
272 write(fd, result, std::size(result));
Ray Essick35ad27f2017-01-30 14:04:11 -0800273 return NO_ERROR;
Andy Hung709b91e2020-04-04 14:23:36 -0700274 } else if (args[i] == prefixOption) {
275 ++i;
276 if (i < n) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000277 prefix = String8(args[i]).c_str();
Andy Hung709b91e2020-04-04 14:23:36 -0700278 }
279 } else if (args[i] == sinceOption) {
280 ++i;
281 if (i < n) {
282 String8 value(args[i]);
283 char *endp;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000284 const char *p = value.c_str();
Andy Hung3ab1b322020-05-18 10:47:31 -0700285 const auto sec = (int64_t)strtoll(p, &endp, 10);
Andy Hung709b91e2020-04-04 14:23:36 -0700286 if (endp == p || *endp != '\0' || sec == 0) {
287 sinceNs = 0;
288 } else if (sec < 0) {
289 sinceNs = systemTime(SYSTEM_TIME_REALTIME) + sec * NANOS_PER_SECOND;
290 } else {
291 sinceNs = sec * NANOS_PER_SECOND;
292 }
293 }
Andy Hung9099a1a2020-04-04 14:23:36 -0700294 } else if (args[i] == unreachableOption) {
295 unreachable = true;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800296 }
297 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700298 std::stringstream result;
Andy Hung17dbaf22019-10-11 14:06:31 -0700299 {
300 std::lock_guard _l(mLock);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800301
Andy Hung17dbaf22019-10-11 14:06:31 -0700302 if (clear) {
Andy Hungc14ee142021-03-10 16:39:02 -0800303 mItemsDiscarded += (int64_t)mItems.size();
Andy Hung17dbaf22019-10-11 14:06:31 -0700304 mItems.clear();
Andy Hung709b91e2020-04-04 14:23:36 -0700305 mAudioAnalytics.clear();
306 } else {
Andy Hung54c73ce2021-03-30 14:25:54 -0700307 result << StringPrintf("Dump of the %s process:\n", kServiceName);
Andy Hung709b91e2020-04-04 14:23:36 -0700308 const char *prefixptr = prefix.size() > 0 ? prefix.c_str() : nullptr;
Andy Hung54c73ce2021-03-30 14:25:54 -0700309 result << dumpHeaders(sinceNs, prefixptr);
310 result << dumpQueue(sinceNs, prefixptr);
Andy Hung709b91e2020-04-04 14:23:36 -0700311
312 // TODO: maybe consider a better way of dumping audio analytics info.
313 const int32_t linesToDump = all ? INT32_MAX : 1000;
314 auto [ dumpString, lines ] = mAudioAnalytics.dump(linesToDump, sinceNs, prefixptr);
Andy Hung54c73ce2021-03-30 14:25:54 -0700315 result << dumpString;
Andy Hung709b91e2020-04-04 14:23:36 -0700316 if (lines == linesToDump) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700317 result << "-- some lines may be truncated --\n";
Andy Hung709b91e2020-04-04 14:23:36 -0700318 }
Andy Hung5be90c82021-03-30 14:30:20 -0700319
Andy Hungf1a23832021-12-13 09:31:55 -0800320 const int32_t heatLinesToDump = all ? INT32_MAX : 20;
321 const auto [ heatDumpString, heatLines] =
322 mAudioAnalytics.dumpHeatMap(heatLinesToDump);
323 result << "\n" << heatDumpString;
324 if (heatLines == heatLinesToDump) {
325 result << "-- some lines may be truncated --\n";
326 }
327
Andy Hungf4eaa462022-03-09 21:53:09 -0800328 const int32_t healthLinesToDump = all ? INT32_MAX : 15;
329 result << "\nHealth Message Log:";
330 const auto [ healthDumpString, healthLines ] =
331 mAudioAnalytics.dumpHealth(healthLinesToDump);
332 result << "\n" << healthDumpString;
333 if (healthLines == healthLinesToDump) {
334 result << "-- some lines may be truncated --\n";
335 }
336
Andy Hungb9427022022-08-18 19:20:48 -0700337 const int32_t spatializerLinesToDump = all ? INT32_MAX : 15;
338 result << "\nSpatializer Message Log:";
339 const auto [ spatializerDumpString, spatializerLines ] =
340 mAudioAnalytics.dumpSpatializer(spatializerLinesToDump);
341 result << "\n" << spatializerDumpString;
342 if (spatializerLines == spatializerLinesToDump) {
343 result << "-- some lines may be truncated --\n";
344 }
345
Andy Hungf1a23832021-12-13 09:31:55 -0800346 result << "\nLogSessionId:\n"
Andy Hungc9b6f8b2021-07-08 10:17:55 -0700347 << mediametrics::ValidateId::get()->dump();
348
Andy Hung5be90c82021-03-30 14:30:20 -0700349 // Dump the statsd atoms we sent out.
Andy Hungf1a23832021-12-13 09:31:55 -0800350 result << "\nStatsd atoms:\n"
Andy Hung5be90c82021-03-30 14:30:20 -0700351 << mStatsdLog->dumpToString(" " /* prefix */,
352 all ? STATSD_LOG_LINES_MAX : STATSD_LOG_LINES_DUMP);
Andy Hung0f7ad8c2020-01-03 13:24:34 -0800353 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700354 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700355 const std::string str = result.str();
356 write(fd, str.c_str(), str.size());
Andy Hung9099a1a2020-04-04 14:23:36 -0700357
358 // Check heap and unreachable memory outside of lock.
359 if (heap) {
360 dprintf(fd, "\nDumping heap:\n");
361 std::string s = dumpMemoryAddresses(100 /* limit */);
362 write(fd, s.c_str(), s.size());
363 }
364 if (unreachable) {
365 dprintf(fd, "\nDumping unreachable memory:\n");
366 // TODO - should limit be an argument parameter?
367 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
368 write(fd, s.c_str(), s.size());
369 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700370 return NO_ERROR;
371}
372
373// dump headers
Andy Hung54c73ce2021-03-30 14:25:54 -0700374std::string MediaMetricsService::dumpHeaders(int64_t sinceNs, const char* prefix)
Ray Essick92d23b42018-01-29 12:10:30 -0800375{
Andy Hung54c73ce2021-03-30 14:25:54 -0700376 std::stringstream result;
Ray Essickf27e9872019-12-07 06:28:46 -0800377 if (mediametrics::Item::isEnabled()) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700378 result << "Metrics gathering: enabled\n";
Ray Essickb5fac8e2016-12-12 11:33:56 -0800379 } else {
Andy Hung54c73ce2021-03-30 14:25:54 -0700380 result << "Metrics gathering: DISABLED via property\n";
Ray Essickb5fac8e2016-12-12 11:33:56 -0800381 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700382 result << StringPrintf(
Andy Hung17dbaf22019-10-11 14:06:31 -0700383 "Since Boot: Submissions: %lld Accepted: %lld\n",
384 (long long)mItemsSubmitted.load(), (long long)mItemsFinalized);
Andy Hung54c73ce2021-03-30 14:25:54 -0700385 result << StringPrintf(
Andy Hung17dbaf22019-10-11 14:06:31 -0700386 "Records Discarded: %lld (by Count: %lld by Expiration: %lld)\n",
387 (long long)mItemsDiscarded, (long long)mItemsDiscardedCount,
388 (long long)mItemsDiscardedExpire);
Andy Hung709b91e2020-04-04 14:23:36 -0700389 if (prefix != nullptr) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700390 result << "Restricting to prefix " << prefix << "\n";
Andy Hung709b91e2020-04-04 14:23:36 -0700391 }
392 if (sinceNs != 0) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700393 result << "Emitting Queue entries more recent than: " << sinceNs << "\n";
Ray Essickb5fac8e2016-12-12 11:33:56 -0800394 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700395 return result.str();
Ray Essick2e9c63b2017-03-29 15:16:44 -0700396}
397
Andy Hung709b91e2020-04-04 14:23:36 -0700398// TODO: should prefix be a set<string>?
Andy Hung54c73ce2021-03-30 14:25:54 -0700399std::string MediaMetricsService::dumpQueue(int64_t sinceNs, const char* prefix)
Ray Essick92d23b42018-01-29 12:10:30 -0800400{
Ray Essick92d23b42018-01-29 12:10:30 -0800401 if (mItems.empty()) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700402 return "empty\n";
Andy Hung709b91e2020-04-04 14:23:36 -0700403 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700404 std::stringstream result;
Andy Hung709b91e2020-04-04 14:23:36 -0700405 int slot = 0;
406 for (const auto &item : mItems) { // TODO: consider std::lower_bound() on mItems
407 if (item->getTimestamp() < sinceNs) { // sinceNs == 0 means all items shown
408 continue;
Ray Essick3938dc62016-11-01 08:56:56 -0700409 }
Andy Hung709b91e2020-04-04 14:23:36 -0700410 if (prefix != nullptr && !startsWith(item->getKey(), prefix)) {
411 ALOGV("%s: omit '%s', it's not '%s'",
412 __func__, item->getKey().c_str(), prefix);
413 continue;
414 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700415 result << StringPrintf("%5d: %s\n", slot, item->toString().c_str());
Andy Hung709b91e2020-04-04 14:23:36 -0700416 slot++;
Ray Essick3938dc62016-11-01 08:56:56 -0700417 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700418 return result.str();
Ray Essick3938dc62016-11-01 08:56:56 -0700419}
420
421//
422// Our Cheap in-core, non-persistent records management.
Ray Essick3938dc62016-11-01 08:56:56 -0700423
Ray Essick72a436b2018-06-14 15:08:13 -0700424// if item != NULL, it's the item we just inserted
425// true == more items eligible to be recovered
Andy Hungf7c14102020-04-18 14:54:08 -0700426bool MediaMetricsService::expirations(const std::shared_ptr<const mediametrics::Item>& item)
Ray Essick92d23b42018-01-29 12:10:30 -0800427{
Ray Essick72a436b2018-06-14 15:08:13 -0700428 bool more = false;
Ray Essicke5db6db2017-11-10 15:54:32 -0800429
Andy Hung17dbaf22019-10-11 14:06:31 -0700430 // check queue size
431 size_t overlimit = 0;
432 if (mMaxRecords > 0 && mItems.size() > mMaxRecords) {
433 overlimit = mItems.size() - mMaxRecords;
434 if (overlimit > mMaxRecordsExpiredAtOnce) {
435 more = true;
436 overlimit = mMaxRecordsExpiredAtOnce;
Ray Essickf65f4212017-08-31 11:41:19 -0700437 }
438 }
439
Andy Hung17dbaf22019-10-11 14:06:31 -0700440 // check queue times
441 size_t expired = 0;
442 if (!more && mMaxRecordAgeNs > 0) {
443 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
444 // we check one at a time, skip search would be more efficient.
445 size_t i = overlimit;
446 for (; i < mItems.size(); ++i) {
447 auto &oitem = mItems[i];
Ray Essickf65f4212017-08-31 11:41:19 -0700448 nsecs_t when = oitem->getTimestamp();
Andy Hung82a074b2019-12-03 14:16:45 -0800449 if (oitem.get() == item.get()) {
Ray Essicke5db6db2017-11-10 15:54:32 -0800450 break;
451 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700452 if (now > when && (now - when) <= mMaxRecordAgeNs) {
Andy Hunged416da2020-03-05 18:42:55 -0800453 break; // Note SYSTEM_TIME_REALTIME may not be monotonic.
Ray Essickf65f4212017-08-31 11:41:19 -0700454 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700455 if (i >= mMaxRecordsExpiredAtOnce) {
Ray Essick72a436b2018-06-14 15:08:13 -0700456 // this represents "one too many"; tell caller there are
457 // more to be reclaimed.
458 more = true;
459 break;
460 }
Ray Essick3938dc62016-11-01 08:56:56 -0700461 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700462 expired = i - overlimit;
Ray Essick3938dc62016-11-01 08:56:56 -0700463 }
Ray Essick72a436b2018-06-14 15:08:13 -0700464
Andy Hung17dbaf22019-10-11 14:06:31 -0700465 if (const size_t toErase = overlimit + expired;
466 toErase > 0) {
Andy Hungc14ee142021-03-10 16:39:02 -0800467 mItemsDiscardedCount += (int64_t)overlimit;
468 mItemsDiscardedExpire += (int64_t)expired;
469 mItemsDiscarded += (int64_t)toErase;
470 mItems.erase(mItems.begin(), mItems.begin() + (ptrdiff_t)toErase); // erase from front
Andy Hung17dbaf22019-10-11 14:06:31 -0700471 }
Ray Essick72a436b2018-06-14 15:08:13 -0700472 return more;
473}
474
Ray Essickf27e9872019-12-07 06:28:46 -0800475void MediaMetricsService::processExpirations()
Ray Essick72a436b2018-06-14 15:08:13 -0700476{
477 bool more;
478 do {
479 sleep(1);
Andy Hung17dbaf22019-10-11 14:06:31 -0700480 std::lock_guard _l(mLock);
Andy Hungf7c14102020-04-18 14:54:08 -0700481 more = expirations(nullptr);
Ray Essick72a436b2018-06-14 15:08:13 -0700482 } while (more);
Ray Essick72a436b2018-06-14 15:08:13 -0700483}
484
Ray Essickf27e9872019-12-07 06:28:46 -0800485void MediaMetricsService::saveItem(const std::shared_ptr<const mediametrics::Item>& item)
Ray Essick72a436b2018-06-14 15:08:13 -0700486{
Andy Hung17dbaf22019-10-11 14:06:31 -0700487 std::lock_guard _l(mLock);
488 // we assume the items are roughly in time order.
489 mItems.emplace_back(item);
Robert Shih2e15aed2021-03-16 18:30:35 -0700490 if (isPullable(item->getKey())) {
491 registerStatsdCallbacksIfNeeded();
492 mPullableItems[item->getKey()].emplace_back(item);
493 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700494 ++mItemsFinalized;
Andy Hungf7c14102020-04-18 14:54:08 -0700495 if (expirations(item)
Andy Hung17dbaf22019-10-11 14:06:31 -0700496 && (!mExpireFuture.valid()
497 || mExpireFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready)) {
498 mExpireFuture = std::async(std::launch::async, [this] { processExpirations(); });
Ray Essick72a436b2018-06-14 15:08:13 -0700499 }
Ray Essick3938dc62016-11-01 08:56:56 -0700500}
501
Andy Hung17dbaf22019-10-11 14:06:31 -0700502/* static */
Ray Essickf27e9872019-12-07 06:28:46 -0800503bool MediaMetricsService::isContentValid(const mediametrics::Item *item, bool isTrusted)
Ray Essickd38e1742017-01-23 15:17:06 -0800504{
Andy Hung17dbaf22019-10-11 14:06:31 -0700505 if (isTrusted) return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800506 // untrusted uids can only send us a limited set of keys
Andy Hung17dbaf22019-10-11 14:06:31 -0700507 const std::string &key = item->getKey();
Andy Hung06f3aba2019-12-03 16:36:42 -0800508 if (startsWith(key, "audio.")) return true;
Edwin Wong8d188352020-02-11 11:59:34 -0800509 if (startsWith(key, "drm.vendor.")) return true;
Robert Shih27914962023-01-12 21:00:16 +0000510 if (startsWith(key, "mediadrm.")) return true;
511
Edwin Wong8d188352020-02-11 11:59:34 -0800512 // the list of allowedKey uses statsd_handlers
513 // in iface_statsd.cpp as reference
514 // drmmanager is from a trusted uid, therefore not needed here
Andy Hung17dbaf22019-10-11 14:06:31 -0700515 for (const char *allowedKey : {
Andy Hung06f3aba2019-12-03 16:36:42 -0800516 // legacy audio
Andy Hung17dbaf22019-10-11 14:06:31 -0700517 "audiopolicy",
518 "audiorecord",
519 "audiothread",
520 "audiotrack",
Andy Hung06f3aba2019-12-03 16:36:42 -0800521 // other media
Andy Hung17dbaf22019-10-11 14:06:31 -0700522 "codec",
Brian Lindahl5c0ba412023-08-28 13:24:22 -0600523 "videofreeze",
524 "videojudder",
Andy Hung17dbaf22019-10-11 14:06:31 -0700525 "extractor",
Edwin Wong8d188352020-02-11 11:59:34 -0800526 "mediadrm",
Santiago Seifert49fb4522020-08-07 13:48:45 +0100527 "mediaparser",
Andy Hung17dbaf22019-10-11 14:06:31 -0700528 "nuplayer",
529 }) {
530 if (key == allowedKey) {
531 return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800532 }
533 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700534 ALOGD("%s: invalid key: %s", __func__, item->toString().c_str());
Ray Essick3938dc62016-11-01 08:56:56 -0700535 return false;
536}
537
Andy Hung17dbaf22019-10-11 14:06:31 -0700538// are we rate limited, normally false
Ray Essickf27e9872019-12-07 06:28:46 -0800539bool MediaMetricsService::isRateLimited(mediametrics::Item *) const
Andy Hung17dbaf22019-10-11 14:06:31 -0700540{
541 return false;
542}
543
Robert Shih2e15aed2021-03-16 18:30:35 -0700544void MediaMetricsService::registerStatsdCallbacksIfNeeded()
545{
546 if (mStatsdRegistered.test_and_set()) {
547 return;
548 }
Vova Sharaienkof58455a2022-09-24 01:47:23 +0000549 auto tag = stats::media_metrics::MEDIA_DRM_ACTIVITY_INFO;
Robert Shih2e15aed2021-03-16 18:30:35 -0700550 auto cb = MediaMetricsService::pullAtomCallback;
551 AStatsManager_setPullAtomCallback(tag, /* metadata */ nullptr, cb, this);
552}
553
554/* static */
555bool MediaMetricsService::isPullable(const std::string &key)
556{
557 static const std::set<std::string> pullableKeys{
558 "mediadrm",
559 };
560 return pullableKeys.count(key);
561}
562
563/* static */
564std::string MediaMetricsService::atomTagToKey(int32_t atomTag)
565{
566 switch (atomTag) {
Vova Sharaienkof58455a2022-09-24 01:47:23 +0000567 case stats::media_metrics::MEDIA_DRM_ACTIVITY_INFO:
Robert Shih2e15aed2021-03-16 18:30:35 -0700568 return "mediadrm";
569 }
570 return {};
571}
572
573/* static */
574AStatsManager_PullAtomCallbackReturn MediaMetricsService::pullAtomCallback(
575 int32_t atomTag, AStatsEventList* data, void* cookie)
576{
577 MediaMetricsService* svc = reinterpret_cast<MediaMetricsService*>(cookie);
578 return svc->pullItems(atomTag, data);
579}
580
581AStatsManager_PullAtomCallbackReturn MediaMetricsService::pullItems(
582 int32_t atomTag, AStatsEventList* data)
583{
584 const std::string key(atomTagToKey(atomTag));
585 if (key.empty()) {
586 return AStatsManager_PULL_SKIP;
587 }
588 std::lock_guard _l(mLock);
Robert Shih58a37f82021-04-19 10:18:50 -0700589 bool dumped = false;
Robert Shih2e15aed2021-03-16 18:30:35 -0700590 for (auto &item : mPullableItems[key]) {
591 if (const auto sitem = item.lock()) {
Robert Shih58a37f82021-04-19 10:18:50 -0700592 dumped |= dump2Statsd(sitem, data, mStatsdLog);
Robert Shih2e15aed2021-03-16 18:30:35 -0700593 }
594 }
595 mPullableItems[key].clear();
Robert Shih58a37f82021-04-19 10:18:50 -0700596 return dumped ? AStatsManager_PULL_SUCCESS : AStatsManager_PULL_SKIP;
Robert Shih2e15aed2021-03-16 18:30:35 -0700597}
Ray Essick3938dc62016-11-01 08:56:56 -0700598} // namespace android