blob: 2ec4ac8bc84300ddcd02361583f18d9e6a14f878 [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;
Andy Hunge4117002024-09-16 17:37:13 -070052
53// Max records to keep in queue which dump out for bugreports.
54static constexpr size_t kMaxRecords = 2500;
Ray Essick72a436b2018-06-14 15:08:13 -070055
56// max we expire in a single call, to constrain how long we hold the
57// mutex, which also constrains how long a client might wait.
Andy Hung17dbaf22019-10-11 14:06:31 -070058static constexpr size_t kMaxExpiredAtOnce = 50;
Ray Essick72a436b2018-06-14 15:08:13 -070059
60// TODO: need to look at tuning kMaxRecords and friends for low-memory devices
Ray Essick2e9c63b2017-03-29 15:16:44 -070061
Andy Hung55aaf522019-12-03 15:07:51 -080062/* static */
Ray Essickf27e9872019-12-07 06:28:46 -080063nsecs_t MediaMetricsService::roundTime(nsecs_t timeNs)
Andy Hung55aaf522019-12-03 15:07:51 -080064{
65 return (timeNs + NANOS_PER_SECOND / 2) / NANOS_PER_SECOND * NANOS_PER_SECOND;
66}
67
Andy Hunga85efab2019-12-23 11:41:29 -080068/* static */
69bool MediaMetricsService::useUidForPackage(
70 const std::string& package, const std::string& installer)
71{
Chih-Hung Hsiehac521522022-06-09 23:16:12 -070072 // NOLINTBEGIN(bugprone-branch-clone)
Andy Hung3ab1b322020-05-18 10:47:31 -070073 if (strchr(package.c_str(), '.') == nullptr) {
Andy Hunga85efab2019-12-23 11:41:29 -080074 return false; // not of form 'com.whatever...'; assume internal and ok
75 } else if (strncmp(package.c_str(), "android.", 8) == 0) {
76 return false; // android.* packages are assumed fine
77 } else if (strncmp(installer.c_str(), "com.android.", 12) == 0) {
78 return false; // from play store
79 } else if (strncmp(installer.c_str(), "com.google.", 11) == 0) {
80 return false; // some google source
81 } else if (strcmp(installer.c_str(), "preload") == 0) {
82 return false; // preloads
83 } else {
84 return true; // we're not sure where it came from, use uid only.
85 }
Chih-Hung Hsiehac521522022-06-09 23:16:12 -070086 // NOLINTEND(bugprone-branch-clone)
Andy Hunga85efab2019-12-23 11:41:29 -080087}
88
Andy Hungce9b6632020-04-28 20:15:17 -070089/* static */
90std::pair<std::string, int64_t>
91MediaMetricsService::getSanitizedPackageNameAndVersionCode(uid_t uid) {
Andy Hungb26a1c82024-08-30 11:54:40 -070092 const std::shared_ptr<const mediautils::UidInfo::Info> info =
93 mediautils::UidInfo::getInfo(uid);
94 if (useUidForPackage(info->package, info->installer)) {
Andy Hungce9b6632020-04-28 20:15:17 -070095 return { std::to_string(uid), /* versionCode */ 0 };
96 } else {
Andy Hungb26a1c82024-08-30 11:54:40 -070097 return { info->package, info->versionCode };
Andy Hungce9b6632020-04-28 20:15:17 -070098 }
99}
100
Ray Essickf27e9872019-12-07 06:28:46 -0800101MediaMetricsService::MediaMetricsService()
Ray Essick2e9c63b2017-03-29 15:16:44 -0700102 : mMaxRecords(kMaxRecords),
Ray Essickf65f4212017-08-31 11:41:19 -0700103 mMaxRecordAgeNs(kMaxRecordAgeNs),
Andy Hung3b4c1f02020-01-23 18:58:32 -0800104 mMaxRecordsExpiredAtOnce(kMaxExpiredAtOnce)
Andy Hung17dbaf22019-10-11 14:06:31 -0700105{
106 ALOGD("%s", __func__);
Ray Essick3938dc62016-11-01 08:56:56 -0700107}
108
Ray Essickf27e9872019-12-07 06:28:46 -0800109MediaMetricsService::~MediaMetricsService()
Andy Hung17dbaf22019-10-11 14:06:31 -0700110{
111 ALOGD("%s", __func__);
112 // the class destructor clears anyhow, but we enforce clearing items first.
Andy Hungc14ee142021-03-10 16:39:02 -0800113 mItemsDiscarded += (int64_t)mItems.size();
Andy Hung17dbaf22019-10-11 14:06:31 -0700114 mItems.clear();
Ray Essick3938dc62016-11-01 08:56:56 -0700115}
116
Ray Essickf27e9872019-12-07 06:28:46 -0800117status_t MediaMetricsService::submitInternal(mediametrics::Item *item, bool release)
Ray Essick92d23b42018-01-29 12:10:30 -0800118{
Andy Hung55aaf522019-12-03 15:07:51 -0800119 // calling PID is 0 for one-way calls.
120 const pid_t pid = IPCThreadState::self()->getCallingPid();
121 const pid_t pid_given = item->getPid();
122 const uid_t uid = IPCThreadState::self()->getCallingUid();
123 const uid_t uid_given = item->getUid();
Ray Essickd38e1742017-01-23 15:17:06 -0800124
Andy Hung55aaf522019-12-03 15:07:51 -0800125 //ALOGD("%s: caller pid=%d uid=%d, item pid=%d uid=%d", __func__,
126 // (int)pid, (int)uid, (int) pid_given, (int)uid_given);
Ray Essickd38e1742017-01-23 15:17:06 -0800127
Andy Hung17dbaf22019-10-11 14:06:31 -0700128 bool isTrusted;
129 switch (uid) {
Andy Hung55aaf522019-12-03 15:07:51 -0800130 case AID_AUDIOSERVER:
131 case AID_BLUETOOTH:
132 case AID_CAMERA:
Andy Hung17dbaf22019-10-11 14:06:31 -0700133 case AID_DRM:
134 case AID_MEDIA:
135 case AID_MEDIA_CODEC:
136 case AID_MEDIA_EX:
137 case AID_MEDIA_DRM:
Andy Hung5d3f2d12020-03-04 19:55:03 -0800138 // case AID_SHELL: // DEBUG ONLY - used for mediametrics_tests to add new keys
Andy Hung55aaf522019-12-03 15:07:51 -0800139 case AID_SYSTEM:
Andy Hung17dbaf22019-10-11 14:06:31 -0700140 // trusted source, only override default values
141 isTrusted = true;
Andy Hung55aaf522019-12-03 15:07:51 -0800142 if (uid_given == (uid_t)-1) {
Ray Essickd38e1742017-01-23 15:17:06 -0800143 item->setUid(uid);
Andy Hung17dbaf22019-10-11 14:06:31 -0700144 }
Andy Hung55aaf522019-12-03 15:07:51 -0800145 if (pid_given == (pid_t)-1) {
146 item->setPid(pid); // if one-way then this is 0.
Andy Hung17dbaf22019-10-11 14:06:31 -0700147 }
148 break;
149 default:
150 isTrusted = false;
Andy Hung55aaf522019-12-03 15:07:51 -0800151 item->setPid(pid); // always use calling pid, if one-way then this is 0.
Andy Hung17dbaf22019-10-11 14:06:31 -0700152 item->setUid(uid);
153 break;
Ray Essickd38e1742017-01-23 15:17:06 -0800154 }
155
Andy Hunga85efab2019-12-23 11:41:29 -0800156 // Overwrite package name and version if the caller was untrusted or empty
157 if (!isTrusted || item->getPkgName().empty()) {
Andy Hung3ab1b322020-05-18 10:47:31 -0700158 const uid_t uidItem = item->getUid();
Andy Hungce9b6632020-04-28 20:15:17 -0700159 const auto [ pkgName, version ] =
Andy Hung3ab1b322020-05-18 10:47:31 -0700160 MediaMetricsService::getSanitizedPackageNameAndVersionCode(uidItem);
Andy Hungce9b6632020-04-28 20:15:17 -0700161 item->setPkgName(pkgName);
162 item->setPkgVersionCode(version);
Adam Stone21c72122017-09-05 19:02:06 -0700163 }
164
Andy Hung5d3f2d12020-03-04 19:55:03 -0800165 ALOGV("%s: isTrusted:%d given uid %d; sanitized uid: %d sanitized pkg: %s "
Andy Hung17dbaf22019-10-11 14:06:31 -0700166 "sanitized pkg version: %lld",
167 __func__,
Andy Hung5d3f2d12020-03-04 19:55:03 -0800168 (int)isTrusted,
Adam Stone21c72122017-09-05 19:02:06 -0700169 uid_given, item->getUid(),
170 item->getPkgName().c_str(),
Andy Hung17dbaf22019-10-11 14:06:31 -0700171 (long long)item->getPkgVersionCode());
Ray Essick3938dc62016-11-01 08:56:56 -0700172
173 mItemsSubmitted++;
174
175 // validate the record; we discard if we don't like it
Andy Hung17dbaf22019-10-11 14:06:31 -0700176 if (isContentValid(item, isTrusted) == false) {
Andy Hunga87e69c2019-10-18 10:07:40 -0700177 if (release) delete item;
178 return PERMISSION_DENIED;
Ray Essick3938dc62016-11-01 08:56:56 -0700179 }
180
Ray Essick92d23b42018-01-29 12:10:30 -0800181 // XXX: if we have a sessionid in the new record, look to make
Ray Essick3938dc62016-11-01 08:56:56 -0700182 // sure it doesn't appear in the finalized list.
Ray Essick3938dc62016-11-01 08:56:56 -0700183
Ray Essick92d23b42018-01-29 12:10:30 -0800184 if (item->count() == 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700185 ALOGV("%s: dropping empty record...", __func__);
Andy Hunga87e69c2019-10-18 10:07:40 -0700186 if (release) delete item;
187 return BAD_VALUE;
Ray Essick3938dc62016-11-01 08:56:56 -0700188 }
Ray Essick92d23b42018-01-29 12:10:30 -0800189
Andy Hung55aaf522019-12-03 15:07:51 -0800190 if (!isTrusted || item->getTimestamp() == 0) {
Muhammad Qureshi087b37c2020-06-16 16:37:36 -0700191 // Statsd logs two times for events: ElapsedRealTimeNs (BOOTTIME) and
Andy Hung3b4c1f02020-01-23 18:58:32 -0800192 // WallClockTimeNs (REALTIME), but currently logs REALTIME to cloud.
Andy Hung55aaf522019-12-03 15:07:51 -0800193 //
Andy Hung3b4c1f02020-01-23 18:58:32 -0800194 // For consistency and correlation with other logging mechanisms
195 // we use REALTIME here.
196 const int64_t now = systemTime(SYSTEM_TIME_REALTIME);
Andy Hung55aaf522019-12-03 15:07:51 -0800197 item->setTimestamp(now);
198 }
199
Andy Hung82a074b2019-12-03 14:16:45 -0800200 // now attach either the item or its dup to a const shared pointer
Ray Essickf27e9872019-12-07 06:28:46 -0800201 std::shared_ptr<const mediametrics::Item> sitem(release ? item : item->dup());
Ray Essick6ce27e52019-02-15 10:58:05 -0800202
Andy Hungc9b6f8b2021-07-08 10:17:55 -0700203 // register log session ids with singleton.
204 if (startsWith(item->getKey(), "metrics.manager")) {
205 std::string logSessionId;
206 if (item->get("logSessionId", &logSessionId)
207 && mediametrics::stringutils::isLogSessionId(logSessionId.c_str())) {
208 mediametrics::ValidateId::get()->registerId(logSessionId);
209 }
210 }
211
Andy Hung06f3aba2019-12-03 16:36:42 -0800212 (void)mAudioAnalytics.submit(sitem, isTrusted);
213
Andy Hung5be90c82021-03-30 14:30:20 -0700214 (void)dump2Statsd(sitem, mStatsdLog); // failure should be logged in function.
Andy Hung82a074b2019-12-03 14:16:45 -0800215 saveItem(sitem);
Andy Hunga87e69c2019-10-18 10:07:40 -0700216 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700217}
218
Ray Essickf27e9872019-12-07 06:28:46 -0800219status_t MediaMetricsService::dump(int fd, const Vector<String16>& args)
Ray Essick3938dc62016-11-01 08:56:56 -0700220{
Ray Essick3938dc62016-11-01 08:56:56 -0700221 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700222 const std::string result = StringPrintf("Permission Denial: "
Ray Essickf27e9872019-12-07 06:28:46 -0800223 "can't dump MediaMetricsService from pid=%d, uid=%d\n",
Ray Essick3938dc62016-11-01 08:56:56 -0700224 IPCThreadState::self()->getCallingPid(),
225 IPCThreadState::self()->getCallingUid());
Andy Hung54c73ce2021-03-30 14:25:54 -0700226 write(fd, result.c_str(), result.size());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800227 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700228 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800229
Andy Hung709b91e2020-04-04 14:23:36 -0700230 static const String16 allOption("--all");
231 static const String16 clearOption("--clear");
Andy Hung9099a1a2020-04-04 14:23:36 -0700232 static const String16 heapOption("--heap");
Andy Hung709b91e2020-04-04 14:23:36 -0700233 static const String16 helpOption("--help");
234 static const String16 prefixOption("--prefix");
235 static const String16 sinceOption("--since");
Andy Hung9099a1a2020-04-04 14:23:36 -0700236 static const String16 unreachableOption("--unreachable");
Andy Hung709b91e2020-04-04 14:23:36 -0700237
238 bool all = false;
239 bool clear = false;
Andy Hung9099a1a2020-04-04 14:23:36 -0700240 bool heap = false;
241 bool unreachable = false;
Andy Hung709b91e2020-04-04 14:23:36 -0700242 int64_t sinceNs = 0;
243 std::string prefix;
Andy Hung9099a1a2020-04-04 14:23:36 -0700244
Andy Hung709b91e2020-04-04 14:23:36 -0700245 const size_t n = args.size();
246 for (size_t i = 0; i < n; i++) {
247 if (args[i] == allOption) {
248 all = true;
249 } else if (args[i] == clearOption) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800250 clear = true;
Andy Hung9099a1a2020-04-04 14:23:36 -0700251 } else if (args[i] == heapOption) {
252 heap = true;
Ray Essick35ad27f2017-01-30 14:04:11 -0800253 } else if (args[i] == helpOption) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700254 // TODO: consider function area dumping.
255 // dumpsys media.metrics audiotrack,codec
256 // or dumpsys media.metrics audiotrack codec
257
Andy Hung54c73ce2021-03-30 14:25:54 -0700258 static constexpr char result[] =
259 "Recognized parameters:\n"
260 "--all show all records\n"
261 "--clear clear out saved records\n"
262 "--heap show heap usage (top 100)\n"
263 "--help display help\n"
264 "--prefix X process records for component X\n"
265 "--since X X < 0: records from -X seconds in the past\n"
266 " X = 0: ignore\n"
267 " X > 0: records from X seconds since Unix epoch\n"
268 "--unreachable show unreachable memory (leaks)\n";
269 write(fd, result, std::size(result));
Ray Essick35ad27f2017-01-30 14:04:11 -0800270 return NO_ERROR;
Andy Hung709b91e2020-04-04 14:23:36 -0700271 } else if (args[i] == prefixOption) {
272 ++i;
273 if (i < n) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000274 prefix = String8(args[i]).c_str();
Andy Hung709b91e2020-04-04 14:23:36 -0700275 }
276 } else if (args[i] == sinceOption) {
277 ++i;
278 if (i < n) {
279 String8 value(args[i]);
280 char *endp;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000281 const char *p = value.c_str();
Andy Hung3ab1b322020-05-18 10:47:31 -0700282 const auto sec = (int64_t)strtoll(p, &endp, 10);
Andy Hung709b91e2020-04-04 14:23:36 -0700283 if (endp == p || *endp != '\0' || sec == 0) {
284 sinceNs = 0;
285 } else if (sec < 0) {
286 sinceNs = systemTime(SYSTEM_TIME_REALTIME) + sec * NANOS_PER_SECOND;
287 } else {
288 sinceNs = sec * NANOS_PER_SECOND;
289 }
290 }
Andy Hung9099a1a2020-04-04 14:23:36 -0700291 } else if (args[i] == unreachableOption) {
292 unreachable = true;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800293 }
294 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700295 std::stringstream result;
Andy Hung17dbaf22019-10-11 14:06:31 -0700296 {
297 std::lock_guard _l(mLock);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800298
Andy Hung17dbaf22019-10-11 14:06:31 -0700299 if (clear) {
Andy Hungc14ee142021-03-10 16:39:02 -0800300 mItemsDiscarded += (int64_t)mItems.size();
Andy Hung17dbaf22019-10-11 14:06:31 -0700301 mItems.clear();
Andy Hung709b91e2020-04-04 14:23:36 -0700302 mAudioAnalytics.clear();
303 } else {
Andy Hung54c73ce2021-03-30 14:25:54 -0700304 result << StringPrintf("Dump of the %s process:\n", kServiceName);
Andy Hung709b91e2020-04-04 14:23:36 -0700305 const char *prefixptr = prefix.size() > 0 ? prefix.c_str() : nullptr;
Andy Hung54c73ce2021-03-30 14:25:54 -0700306 result << dumpHeaders(sinceNs, prefixptr);
307 result << dumpQueue(sinceNs, prefixptr);
Andy Hung709b91e2020-04-04 14:23:36 -0700308
309 // TODO: maybe consider a better way of dumping audio analytics info.
310 const int32_t linesToDump = all ? INT32_MAX : 1000;
Andy Hunge4117002024-09-16 17:37:13 -0700311 auto [ dumpString, lines ] = mAudioAnalytics.dump(
312 all, linesToDump, sinceNs, prefixptr);
Andy Hung54c73ce2021-03-30 14:25:54 -0700313 result << dumpString;
Andy Hung709b91e2020-04-04 14:23:36 -0700314 if (lines == linesToDump) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700315 result << "-- some lines may be truncated --\n";
Andy Hung709b91e2020-04-04 14:23:36 -0700316 }
Andy Hung5be90c82021-03-30 14:30:20 -0700317
Andy Hungf1a23832021-12-13 09:31:55 -0800318 const int32_t heatLinesToDump = all ? INT32_MAX : 20;
319 const auto [ heatDumpString, heatLines] =
320 mAudioAnalytics.dumpHeatMap(heatLinesToDump);
321 result << "\n" << heatDumpString;
322 if (heatLines == heatLinesToDump) {
323 result << "-- some lines may be truncated --\n";
324 }
325
Andy Hungf4eaa462022-03-09 21:53:09 -0800326 const int32_t healthLinesToDump = all ? INT32_MAX : 15;
327 result << "\nHealth Message Log:";
328 const auto [ healthDumpString, healthLines ] =
329 mAudioAnalytics.dumpHealth(healthLinesToDump);
330 result << "\n" << healthDumpString;
331 if (healthLines == healthLinesToDump) {
332 result << "-- some lines may be truncated --\n";
333 }
334
Andy Hungb9427022022-08-18 19:20:48 -0700335 const int32_t spatializerLinesToDump = all ? INT32_MAX : 15;
336 result << "\nSpatializer Message Log:";
337 const auto [ spatializerDumpString, spatializerLines ] =
338 mAudioAnalytics.dumpSpatializer(spatializerLinesToDump);
339 result << "\n" << spatializerDumpString;
340 if (spatializerLines == spatializerLinesToDump) {
341 result << "-- some lines may be truncated --\n";
342 }
343
Andy Hungf1a23832021-12-13 09:31:55 -0800344 result << "\nLogSessionId:\n"
Andy Hungc9b6f8b2021-07-08 10:17:55 -0700345 << mediametrics::ValidateId::get()->dump();
346
Andy Hung5be90c82021-03-30 14:30:20 -0700347 // Dump the statsd atoms we sent out.
Andy Hungf1a23832021-12-13 09:31:55 -0800348 result << "\nStatsd atoms:\n"
Andy Hung5be90c82021-03-30 14:30:20 -0700349 << mStatsdLog->dumpToString(" " /* prefix */,
350 all ? STATSD_LOG_LINES_MAX : STATSD_LOG_LINES_DUMP);
Andy Hung0f7ad8c2020-01-03 13:24:34 -0800351 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700352 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700353 const std::string str = result.str();
354 write(fd, str.c_str(), str.size());
Andy Hung9099a1a2020-04-04 14:23:36 -0700355
356 // Check heap and unreachable memory outside of lock.
357 if (heap) {
358 dprintf(fd, "\nDumping heap:\n");
359 std::string s = dumpMemoryAddresses(100 /* limit */);
360 write(fd, s.c_str(), s.size());
361 }
362 if (unreachable) {
363 dprintf(fd, "\nDumping unreachable memory:\n");
364 // TODO - should limit be an argument parameter?
365 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
366 write(fd, s.c_str(), s.size());
367 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700368 return NO_ERROR;
369}
370
371// dump headers
Andy Hung54c73ce2021-03-30 14:25:54 -0700372std::string MediaMetricsService::dumpHeaders(int64_t sinceNs, const char* prefix)
Ray Essick92d23b42018-01-29 12:10:30 -0800373{
Andy Hung54c73ce2021-03-30 14:25:54 -0700374 std::stringstream result;
Ray Essickf27e9872019-12-07 06:28:46 -0800375 if (mediametrics::Item::isEnabled()) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700376 result << "Metrics gathering: enabled\n";
Ray Essickb5fac8e2016-12-12 11:33:56 -0800377 } else {
Andy Hung54c73ce2021-03-30 14:25:54 -0700378 result << "Metrics gathering: DISABLED via property\n";
Ray Essickb5fac8e2016-12-12 11:33:56 -0800379 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700380 result << StringPrintf(
Andy Hung17dbaf22019-10-11 14:06:31 -0700381 "Since Boot: Submissions: %lld Accepted: %lld\n",
382 (long long)mItemsSubmitted.load(), (long long)mItemsFinalized);
Andy Hung54c73ce2021-03-30 14:25:54 -0700383 result << StringPrintf(
Andy Hung17dbaf22019-10-11 14:06:31 -0700384 "Records Discarded: %lld (by Count: %lld by Expiration: %lld)\n",
385 (long long)mItemsDiscarded, (long long)mItemsDiscardedCount,
386 (long long)mItemsDiscardedExpire);
Andy Hung709b91e2020-04-04 14:23:36 -0700387 if (prefix != nullptr) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700388 result << "Restricting to prefix " << prefix << "\n";
Andy Hung709b91e2020-04-04 14:23:36 -0700389 }
390 if (sinceNs != 0) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700391 result << "Emitting Queue entries more recent than: " << sinceNs << "\n";
Ray Essickb5fac8e2016-12-12 11:33:56 -0800392 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700393 return result.str();
Ray Essick2e9c63b2017-03-29 15:16:44 -0700394}
395
Andy Hung709b91e2020-04-04 14:23:36 -0700396// TODO: should prefix be a set<string>?
Andy Hung54c73ce2021-03-30 14:25:54 -0700397std::string MediaMetricsService::dumpQueue(int64_t sinceNs, const char* prefix)
Ray Essick92d23b42018-01-29 12:10:30 -0800398{
Ray Essick92d23b42018-01-29 12:10:30 -0800399 if (mItems.empty()) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700400 return "empty\n";
Andy Hung709b91e2020-04-04 14:23:36 -0700401 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700402 std::stringstream result;
Andy Hung709b91e2020-04-04 14:23:36 -0700403 int slot = 0;
404 for (const auto &item : mItems) { // TODO: consider std::lower_bound() on mItems
405 if (item->getTimestamp() < sinceNs) { // sinceNs == 0 means all items shown
406 continue;
Ray Essick3938dc62016-11-01 08:56:56 -0700407 }
Andy Hung709b91e2020-04-04 14:23:36 -0700408 if (prefix != nullptr && !startsWith(item->getKey(), prefix)) {
409 ALOGV("%s: omit '%s', it's not '%s'",
410 __func__, item->getKey().c_str(), prefix);
411 continue;
412 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700413 result << StringPrintf("%5d: %s\n", slot, item->toString().c_str());
Andy Hung709b91e2020-04-04 14:23:36 -0700414 slot++;
Ray Essick3938dc62016-11-01 08:56:56 -0700415 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700416 return result.str();
Ray Essick3938dc62016-11-01 08:56:56 -0700417}
418
419//
420// Our Cheap in-core, non-persistent records management.
Ray Essick3938dc62016-11-01 08:56:56 -0700421
Ray Essick72a436b2018-06-14 15:08:13 -0700422// if item != NULL, it's the item we just inserted
423// true == more items eligible to be recovered
Andy Hungf7c14102020-04-18 14:54:08 -0700424bool MediaMetricsService::expirations(const std::shared_ptr<const mediametrics::Item>& item)
Ray Essick92d23b42018-01-29 12:10:30 -0800425{
Ray Essick72a436b2018-06-14 15:08:13 -0700426 bool more = false;
Ray Essicke5db6db2017-11-10 15:54:32 -0800427
Andy Hung17dbaf22019-10-11 14:06:31 -0700428 // check queue size
429 size_t overlimit = 0;
430 if (mMaxRecords > 0 && mItems.size() > mMaxRecords) {
431 overlimit = mItems.size() - mMaxRecords;
432 if (overlimit > mMaxRecordsExpiredAtOnce) {
433 more = true;
434 overlimit = mMaxRecordsExpiredAtOnce;
Ray Essickf65f4212017-08-31 11:41:19 -0700435 }
436 }
437
Andy Hung17dbaf22019-10-11 14:06:31 -0700438 // check queue times
439 size_t expired = 0;
440 if (!more && mMaxRecordAgeNs > 0) {
441 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
442 // we check one at a time, skip search would be more efficient.
443 size_t i = overlimit;
444 for (; i < mItems.size(); ++i) {
445 auto &oitem = mItems[i];
Ray Essickf65f4212017-08-31 11:41:19 -0700446 nsecs_t when = oitem->getTimestamp();
Andy Hung82a074b2019-12-03 14:16:45 -0800447 if (oitem.get() == item.get()) {
Ray Essicke5db6db2017-11-10 15:54:32 -0800448 break;
449 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700450 if (now > when && (now - when) <= mMaxRecordAgeNs) {
Andy Hunged416da2020-03-05 18:42:55 -0800451 break; // Note SYSTEM_TIME_REALTIME may not be monotonic.
Ray Essickf65f4212017-08-31 11:41:19 -0700452 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700453 if (i >= mMaxRecordsExpiredAtOnce) {
Ray Essick72a436b2018-06-14 15:08:13 -0700454 // this represents "one too many"; tell caller there are
455 // more to be reclaimed.
456 more = true;
457 break;
458 }
Ray Essick3938dc62016-11-01 08:56:56 -0700459 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700460 expired = i - overlimit;
Ray Essick3938dc62016-11-01 08:56:56 -0700461 }
Ray Essick72a436b2018-06-14 15:08:13 -0700462
Andy Hung17dbaf22019-10-11 14:06:31 -0700463 if (const size_t toErase = overlimit + expired;
464 toErase > 0) {
Andy Hungc14ee142021-03-10 16:39:02 -0800465 mItemsDiscardedCount += (int64_t)overlimit;
466 mItemsDiscardedExpire += (int64_t)expired;
467 mItemsDiscarded += (int64_t)toErase;
468 mItems.erase(mItems.begin(), mItems.begin() + (ptrdiff_t)toErase); // erase from front
Andy Hung17dbaf22019-10-11 14:06:31 -0700469 }
Ray Essick72a436b2018-06-14 15:08:13 -0700470 return more;
471}
472
Ray Essickf27e9872019-12-07 06:28:46 -0800473void MediaMetricsService::processExpirations()
Ray Essick72a436b2018-06-14 15:08:13 -0700474{
475 bool more;
476 do {
477 sleep(1);
Andy Hung17dbaf22019-10-11 14:06:31 -0700478 std::lock_guard _l(mLock);
Andy Hungf7c14102020-04-18 14:54:08 -0700479 more = expirations(nullptr);
Ray Essick72a436b2018-06-14 15:08:13 -0700480 } while (more);
Ray Essick72a436b2018-06-14 15:08:13 -0700481}
482
Ray Essickf27e9872019-12-07 06:28:46 -0800483void MediaMetricsService::saveItem(const std::shared_ptr<const mediametrics::Item>& item)
Ray Essick72a436b2018-06-14 15:08:13 -0700484{
Andy Hung17dbaf22019-10-11 14:06:31 -0700485 std::lock_guard _l(mLock);
486 // we assume the items are roughly in time order.
487 mItems.emplace_back(item);
Robert Shih2e15aed2021-03-16 18:30:35 -0700488 if (isPullable(item->getKey())) {
489 registerStatsdCallbacksIfNeeded();
490 mPullableItems[item->getKey()].emplace_back(item);
491 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700492 ++mItemsFinalized;
Andy Hungf7c14102020-04-18 14:54:08 -0700493 if (expirations(item)
Andy Hung17dbaf22019-10-11 14:06:31 -0700494 && (!mExpireFuture.valid()
495 || mExpireFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready)) {
496 mExpireFuture = std::async(std::launch::async, [this] { processExpirations(); });
Ray Essick72a436b2018-06-14 15:08:13 -0700497 }
Ray Essick3938dc62016-11-01 08:56:56 -0700498}
499
Andy Hung17dbaf22019-10-11 14:06:31 -0700500/* static */
Ray Essickf27e9872019-12-07 06:28:46 -0800501bool MediaMetricsService::isContentValid(const mediametrics::Item *item, bool isTrusted)
Ray Essickd38e1742017-01-23 15:17:06 -0800502{
Andy Hung17dbaf22019-10-11 14:06:31 -0700503 if (isTrusted) return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800504 // untrusted uids can only send us a limited set of keys
Andy Hung17dbaf22019-10-11 14:06:31 -0700505 const std::string &key = item->getKey();
Andy Hung06f3aba2019-12-03 16:36:42 -0800506 if (startsWith(key, "audio.")) return true;
Edwin Wong8d188352020-02-11 11:59:34 -0800507 if (startsWith(key, "drm.vendor.")) return true;
Robert Shih27914962023-01-12 21:00:16 +0000508 if (startsWith(key, "mediadrm.")) return true;
509
Edwin Wong8d188352020-02-11 11:59:34 -0800510 // the list of allowedKey uses statsd_handlers
511 // in iface_statsd.cpp as reference
512 // drmmanager is from a trusted uid, therefore not needed here
Andy Hung17dbaf22019-10-11 14:06:31 -0700513 for (const char *allowedKey : {
Andy Hung06f3aba2019-12-03 16:36:42 -0800514 // legacy audio
Andy Hung17dbaf22019-10-11 14:06:31 -0700515 "audiopolicy",
516 "audiorecord",
517 "audiothread",
518 "audiotrack",
Andy Hung06f3aba2019-12-03 16:36:42 -0800519 // other media
Andy Hung17dbaf22019-10-11 14:06:31 -0700520 "codec",
Brian Lindahl5c0ba412023-08-28 13:24:22 -0600521 "videofreeze",
522 "videojudder",
Andy Hung17dbaf22019-10-11 14:06:31 -0700523 "extractor",
Edwin Wong8d188352020-02-11 11:59:34 -0800524 "mediadrm",
Santiago Seifert49fb4522020-08-07 13:48:45 +0100525 "mediaparser",
Andy Hung17dbaf22019-10-11 14:06:31 -0700526 "nuplayer",
527 }) {
528 if (key == allowedKey) {
529 return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800530 }
531 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700532 ALOGD("%s: invalid key: %s", __func__, item->toString().c_str());
Ray Essick3938dc62016-11-01 08:56:56 -0700533 return false;
534}
535
Andy Hung17dbaf22019-10-11 14:06:31 -0700536// are we rate limited, normally false
Ray Essickf27e9872019-12-07 06:28:46 -0800537bool MediaMetricsService::isRateLimited(mediametrics::Item *) const
Andy Hung17dbaf22019-10-11 14:06:31 -0700538{
539 return false;
540}
541
Robert Shih2e15aed2021-03-16 18:30:35 -0700542void MediaMetricsService::registerStatsdCallbacksIfNeeded()
543{
544 if (mStatsdRegistered.test_and_set()) {
545 return;
546 }
Vova Sharaienkof58455a2022-09-24 01:47:23 +0000547 auto tag = stats::media_metrics::MEDIA_DRM_ACTIVITY_INFO;
Robert Shih2e15aed2021-03-16 18:30:35 -0700548 auto cb = MediaMetricsService::pullAtomCallback;
549 AStatsManager_setPullAtomCallback(tag, /* metadata */ nullptr, cb, this);
550}
551
552/* static */
553bool MediaMetricsService::isPullable(const std::string &key)
554{
555 static const std::set<std::string> pullableKeys{
556 "mediadrm",
557 };
558 return pullableKeys.count(key);
559}
560
561/* static */
562std::string MediaMetricsService::atomTagToKey(int32_t atomTag)
563{
564 switch (atomTag) {
Vova Sharaienkof58455a2022-09-24 01:47:23 +0000565 case stats::media_metrics::MEDIA_DRM_ACTIVITY_INFO:
Robert Shih2e15aed2021-03-16 18:30:35 -0700566 return "mediadrm";
567 }
568 return {};
569}
570
571/* static */
572AStatsManager_PullAtomCallbackReturn MediaMetricsService::pullAtomCallback(
573 int32_t atomTag, AStatsEventList* data, void* cookie)
574{
575 MediaMetricsService* svc = reinterpret_cast<MediaMetricsService*>(cookie);
576 return svc->pullItems(atomTag, data);
577}
578
579AStatsManager_PullAtomCallbackReturn MediaMetricsService::pullItems(
580 int32_t atomTag, AStatsEventList* data)
581{
582 const std::string key(atomTagToKey(atomTag));
583 if (key.empty()) {
584 return AStatsManager_PULL_SKIP;
585 }
586 std::lock_guard _l(mLock);
Robert Shih58a37f82021-04-19 10:18:50 -0700587 bool dumped = false;
Robert Shih2e15aed2021-03-16 18:30:35 -0700588 for (auto &item : mPullableItems[key]) {
589 if (const auto sitem = item.lock()) {
Robert Shih58a37f82021-04-19 10:18:50 -0700590 dumped |= dump2Statsd(sitem, data, mStatsdLog);
Robert Shih2e15aed2021-03-16 18:30:35 -0700591 }
592 }
593 mPullableItems[key].clear();
Robert Shih58a37f82021-04-19 10:18:50 -0700594 return dumped ? AStatsManager_PULL_SUCCESS : AStatsManager_PULL_SKIP;
Robert Shih2e15aed2021-03-16 18:30:35 -0700595}
Ray Essick3938dc62016-11-01 08:56:56 -0700596} // namespace android