blob: 832148168f275e8d3ed173df3988d7bf320d52f6 [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"
Robert Shih2e15aed2021-03-16 18:30:35 -070022#include "iface_statsd.h"
Ray Essick3938dc62016-11-01 08:56:56 -070023
Andy Hung17dbaf22019-10-11 14:06:31 -070024#include <pwd.h> //getpwuid
25
Andy Hung54c73ce2021-03-30 14:25:54 -070026#include <android-base/stringprintf.h>
Andy Hung17dbaf22019-10-11 14:06:31 -070027#include <android/content/pm/IPackageManagerNative.h> // package info
Andy Hung55aaf522019-12-03 15:07:51 -080028#include <audio_utils/clock.h> // clock conversions
Andy Hung17dbaf22019-10-11 14:06:31 -070029#include <binder/IPCThreadState.h> // get calling uid
Andy Hung49ca44e2020-11-10 22:14:58 -080030#include <binder/IServiceManager.h> // checkCallingPermission
Andy Hung17dbaf22019-10-11 14:06:31 -070031#include <cutils/properties.h> // for property_get
Andy Hung9099a1a2020-04-04 14:23:36 -070032#include <mediautils/MemoryLeakTrackUtil.h>
33#include <memunreachable/memunreachable.h>
Andy Hung17dbaf22019-10-11 14:06:31 -070034#include <private/android_filesystem_config.h> // UID
Robert Shih2e15aed2021-03-16 18:30:35 -070035#include <statslog.h>
36
37#include <set>
Andy Hung17dbaf22019-10-11 14:06:31 -070038
Ray Essick3938dc62016-11-01 08:56:56 -070039namespace android {
40
Andy Hung54c73ce2021-03-30 14:25:54 -070041using base::StringPrintf;
Andy Hung3ab1b322020-05-18 10:47:31 -070042using mediametrics::Item;
43using mediametrics::startsWith;
Andy Hung1efc9c62019-12-03 13:43:33 -080044
Ray Essickf65f4212017-08-31 11:41:19 -070045// individual records kept in memory: age or count
Ray Essick72a436b2018-06-14 15:08:13 -070046// age: <= 28 hours (1 1/6 days)
Ray Essickf65f4212017-08-31 11:41:19 -070047// count: hard limit of # records
48// (0 for either of these disables that threshold)
Ray Essick72a436b2018-06-14 15:08:13 -070049//
Andy Hung17dbaf22019-10-11 14:06:31 -070050static constexpr nsecs_t kMaxRecordAgeNs = 28 * 3600 * NANOS_PER_SECOND;
Ray Essick23f4d6c2019-06-20 10:16:37 -070051// 2019/6: average daily per device is currently 375-ish;
52// setting this to 2000 is large enough to catch most devices
53// we'll lose some data on very very media-active devices, but only for
54// the gms collection; statsd will have already covered those for us.
55// This also retains enough information to help with bugreports
Andy Hung17dbaf22019-10-11 14:06:31 -070056static constexpr size_t kMaxRecords = 2000;
Ray Essick72a436b2018-06-14 15:08:13 -070057
58// max we expire in a single call, to constrain how long we hold the
59// mutex, which also constrains how long a client might wait.
Andy Hung17dbaf22019-10-11 14:06:31 -070060static constexpr size_t kMaxExpiredAtOnce = 50;
Ray Essick72a436b2018-06-14 15:08:13 -070061
62// TODO: need to look at tuning kMaxRecords and friends for low-memory devices
Ray Essick2e9c63b2017-03-29 15:16:44 -070063
Andy Hung55aaf522019-12-03 15:07:51 -080064/* static */
Ray Essickf27e9872019-12-07 06:28:46 -080065nsecs_t MediaMetricsService::roundTime(nsecs_t timeNs)
Andy Hung55aaf522019-12-03 15:07:51 -080066{
67 return (timeNs + NANOS_PER_SECOND / 2) / NANOS_PER_SECOND * NANOS_PER_SECOND;
68}
69
Andy Hunga85efab2019-12-23 11:41:29 -080070/* static */
71bool MediaMetricsService::useUidForPackage(
72 const std::string& package, const std::string& installer)
73{
Andy Hung3ab1b322020-05-18 10:47:31 -070074 if (strchr(package.c_str(), '.') == nullptr) {
Andy Hunga85efab2019-12-23 11:41:29 -080075 return false; // not of form 'com.whatever...'; assume internal and ok
76 } else if (strncmp(package.c_str(), "android.", 8) == 0) {
77 return false; // android.* packages are assumed fine
78 } else if (strncmp(installer.c_str(), "com.android.", 12) == 0) {
79 return false; // from play store
80 } else if (strncmp(installer.c_str(), "com.google.", 11) == 0) {
81 return false; // some google source
82 } else if (strcmp(installer.c_str(), "preload") == 0) {
83 return false; // preloads
84 } else {
85 return true; // we're not sure where it came from, use uid only.
86 }
87}
88
Andy Hungce9b6632020-04-28 20:15:17 -070089/* static */
90std::pair<std::string, int64_t>
91MediaMetricsService::getSanitizedPackageNameAndVersionCode(uid_t uid) {
92 // Meyer's singleton, initialized on first access.
93 // mUidInfo is locked internally.
94 static mediautils::UidInfo uidInfo;
95
96 // get info.
97 mediautils::UidInfo::Info info = uidInfo.getInfo(uid);
98 if (useUidForPackage(info.package, info.installer)) {
99 return { std::to_string(uid), /* versionCode */ 0 };
100 } else {
101 return { info.package, info.versionCode };
102 }
103}
104
Ray Essickf27e9872019-12-07 06:28:46 -0800105MediaMetricsService::MediaMetricsService()
Ray Essick2e9c63b2017-03-29 15:16:44 -0700106 : mMaxRecords(kMaxRecords),
Ray Essickf65f4212017-08-31 11:41:19 -0700107 mMaxRecordAgeNs(kMaxRecordAgeNs),
Andy Hung3b4c1f02020-01-23 18:58:32 -0800108 mMaxRecordsExpiredAtOnce(kMaxExpiredAtOnce)
Andy Hung17dbaf22019-10-11 14:06:31 -0700109{
110 ALOGD("%s", __func__);
Ray Essick3938dc62016-11-01 08:56:56 -0700111}
112
Ray Essickf27e9872019-12-07 06:28:46 -0800113MediaMetricsService::~MediaMetricsService()
Andy Hung17dbaf22019-10-11 14:06:31 -0700114{
115 ALOGD("%s", __func__);
116 // the class destructor clears anyhow, but we enforce clearing items first.
Andy Hungc14ee142021-03-10 16:39:02 -0800117 mItemsDiscarded += (int64_t)mItems.size();
Andy Hung17dbaf22019-10-11 14:06:31 -0700118 mItems.clear();
Ray Essick3938dc62016-11-01 08:56:56 -0700119}
120
Ray Essickf27e9872019-12-07 06:28:46 -0800121status_t MediaMetricsService::submitInternal(mediametrics::Item *item, bool release)
Ray Essick92d23b42018-01-29 12:10:30 -0800122{
Andy Hung55aaf522019-12-03 15:07:51 -0800123 // calling PID is 0 for one-way calls.
124 const pid_t pid = IPCThreadState::self()->getCallingPid();
125 const pid_t pid_given = item->getPid();
126 const uid_t uid = IPCThreadState::self()->getCallingUid();
127 const uid_t uid_given = item->getUid();
Ray Essickd38e1742017-01-23 15:17:06 -0800128
Andy Hung55aaf522019-12-03 15:07:51 -0800129 //ALOGD("%s: caller pid=%d uid=%d, item pid=%d uid=%d", __func__,
130 // (int)pid, (int)uid, (int) pid_given, (int)uid_given);
Ray Essickd38e1742017-01-23 15:17:06 -0800131
Andy Hung17dbaf22019-10-11 14:06:31 -0700132 bool isTrusted;
133 switch (uid) {
Andy Hung55aaf522019-12-03 15:07:51 -0800134 case AID_AUDIOSERVER:
135 case AID_BLUETOOTH:
136 case AID_CAMERA:
Andy Hung17dbaf22019-10-11 14:06:31 -0700137 case AID_DRM:
138 case AID_MEDIA:
139 case AID_MEDIA_CODEC:
140 case AID_MEDIA_EX:
141 case AID_MEDIA_DRM:
Andy Hung5d3f2d12020-03-04 19:55:03 -0800142 // case AID_SHELL: // DEBUG ONLY - used for mediametrics_tests to add new keys
Andy Hung55aaf522019-12-03 15:07:51 -0800143 case AID_SYSTEM:
Andy Hung17dbaf22019-10-11 14:06:31 -0700144 // trusted source, only override default values
145 isTrusted = true;
Andy Hung55aaf522019-12-03 15:07:51 -0800146 if (uid_given == (uid_t)-1) {
Ray Essickd38e1742017-01-23 15:17:06 -0800147 item->setUid(uid);
Andy Hung17dbaf22019-10-11 14:06:31 -0700148 }
Andy Hung55aaf522019-12-03 15:07:51 -0800149 if (pid_given == (pid_t)-1) {
150 item->setPid(pid); // if one-way then this is 0.
Andy Hung17dbaf22019-10-11 14:06:31 -0700151 }
152 break;
153 default:
154 isTrusted = false;
Andy Hung55aaf522019-12-03 15:07:51 -0800155 item->setPid(pid); // always use calling pid, if one-way then this is 0.
Andy Hung17dbaf22019-10-11 14:06:31 -0700156 item->setUid(uid);
157 break;
Ray Essickd38e1742017-01-23 15:17:06 -0800158 }
159
Andy Hunga85efab2019-12-23 11:41:29 -0800160 // Overwrite package name and version if the caller was untrusted or empty
161 if (!isTrusted || item->getPkgName().empty()) {
Andy Hung3ab1b322020-05-18 10:47:31 -0700162 const uid_t uidItem = item->getUid();
Andy Hungce9b6632020-04-28 20:15:17 -0700163 const auto [ pkgName, version ] =
Andy Hung3ab1b322020-05-18 10:47:31 -0700164 MediaMetricsService::getSanitizedPackageNameAndVersionCode(uidItem);
Andy Hungce9b6632020-04-28 20:15:17 -0700165 item->setPkgName(pkgName);
166 item->setPkgVersionCode(version);
Adam Stone21c72122017-09-05 19:02:06 -0700167 }
168
Andy Hung5d3f2d12020-03-04 19:55:03 -0800169 ALOGV("%s: isTrusted:%d given uid %d; sanitized uid: %d sanitized pkg: %s "
Andy Hung17dbaf22019-10-11 14:06:31 -0700170 "sanitized pkg version: %lld",
171 __func__,
Andy Hung5d3f2d12020-03-04 19:55:03 -0800172 (int)isTrusted,
Adam Stone21c72122017-09-05 19:02:06 -0700173 uid_given, item->getUid(),
174 item->getPkgName().c_str(),
Andy Hung17dbaf22019-10-11 14:06:31 -0700175 (long long)item->getPkgVersionCode());
Ray Essick3938dc62016-11-01 08:56:56 -0700176
177 mItemsSubmitted++;
178
179 // validate the record; we discard if we don't like it
Andy Hung17dbaf22019-10-11 14:06:31 -0700180 if (isContentValid(item, isTrusted) == false) {
Andy Hunga87e69c2019-10-18 10:07:40 -0700181 if (release) delete item;
182 return PERMISSION_DENIED;
Ray Essick3938dc62016-11-01 08:56:56 -0700183 }
184
Ray Essick92d23b42018-01-29 12:10:30 -0800185 // XXX: if we have a sessionid in the new record, look to make
Ray Essick3938dc62016-11-01 08:56:56 -0700186 // sure it doesn't appear in the finalized list.
Ray Essick3938dc62016-11-01 08:56:56 -0700187
Ray Essick92d23b42018-01-29 12:10:30 -0800188 if (item->count() == 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700189 ALOGV("%s: dropping empty record...", __func__);
Andy Hunga87e69c2019-10-18 10:07:40 -0700190 if (release) delete item;
191 return BAD_VALUE;
Ray Essick3938dc62016-11-01 08:56:56 -0700192 }
Ray Essick92d23b42018-01-29 12:10:30 -0800193
Andy Hung55aaf522019-12-03 15:07:51 -0800194 if (!isTrusted || item->getTimestamp() == 0) {
Muhammad Qureshi087b37c2020-06-16 16:37:36 -0700195 // Statsd logs two times for events: ElapsedRealTimeNs (BOOTTIME) and
Andy Hung3b4c1f02020-01-23 18:58:32 -0800196 // WallClockTimeNs (REALTIME), but currently logs REALTIME to cloud.
Andy Hung55aaf522019-12-03 15:07:51 -0800197 //
Andy Hung3b4c1f02020-01-23 18:58:32 -0800198 // For consistency and correlation with other logging mechanisms
199 // we use REALTIME here.
200 const int64_t now = systemTime(SYSTEM_TIME_REALTIME);
Andy Hung55aaf522019-12-03 15:07:51 -0800201 item->setTimestamp(now);
202 }
203
Andy Hung82a074b2019-12-03 14:16:45 -0800204 // now attach either the item or its dup to a const shared pointer
Ray Essickf27e9872019-12-07 06:28:46 -0800205 std::shared_ptr<const mediametrics::Item> sitem(release ? item : item->dup());
Ray Essick6ce27e52019-02-15 10:58:05 -0800206
Andy Hung06f3aba2019-12-03 16:36:42 -0800207 (void)mAudioAnalytics.submit(sitem, isTrusted);
208
Andy Hung5be90c82021-03-30 14:30:20 -0700209 (void)dump2Statsd(sitem, mStatsdLog); // failure should be logged in function.
Andy Hung82a074b2019-12-03 14:16:45 -0800210 saveItem(sitem);
Andy Hunga87e69c2019-10-18 10:07:40 -0700211 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700212}
213
Ray Essickf27e9872019-12-07 06:28:46 -0800214status_t MediaMetricsService::dump(int fd, const Vector<String16>& args)
Ray Essick3938dc62016-11-01 08:56:56 -0700215{
Ray Essick3938dc62016-11-01 08:56:56 -0700216 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700217 const std::string result = StringPrintf("Permission Denial: "
Ray Essickf27e9872019-12-07 06:28:46 -0800218 "can't dump MediaMetricsService from pid=%d, uid=%d\n",
Ray Essick3938dc62016-11-01 08:56:56 -0700219 IPCThreadState::self()->getCallingPid(),
220 IPCThreadState::self()->getCallingUid());
Andy Hung54c73ce2021-03-30 14:25:54 -0700221 write(fd, result.c_str(), result.size());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800222 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700223 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800224
Andy Hung709b91e2020-04-04 14:23:36 -0700225 static const String16 allOption("--all");
226 static const String16 clearOption("--clear");
Andy Hung9099a1a2020-04-04 14:23:36 -0700227 static const String16 heapOption("--heap");
Andy Hung709b91e2020-04-04 14:23:36 -0700228 static const String16 helpOption("--help");
229 static const String16 prefixOption("--prefix");
230 static const String16 sinceOption("--since");
Andy Hung9099a1a2020-04-04 14:23:36 -0700231 static const String16 unreachableOption("--unreachable");
Andy Hung709b91e2020-04-04 14:23:36 -0700232
233 bool all = false;
234 bool clear = false;
Andy Hung9099a1a2020-04-04 14:23:36 -0700235 bool heap = false;
236 bool unreachable = false;
Andy Hung709b91e2020-04-04 14:23:36 -0700237 int64_t sinceNs = 0;
238 std::string prefix;
Andy Hung9099a1a2020-04-04 14:23:36 -0700239
Andy Hung709b91e2020-04-04 14:23:36 -0700240 const size_t n = args.size();
241 for (size_t i = 0; i < n; i++) {
242 if (args[i] == allOption) {
243 all = true;
244 } else if (args[i] == clearOption) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800245 clear = true;
Andy Hung9099a1a2020-04-04 14:23:36 -0700246 } else if (args[i] == heapOption) {
247 heap = true;
Ray Essick35ad27f2017-01-30 14:04:11 -0800248 } else if (args[i] == helpOption) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700249 // TODO: consider function area dumping.
250 // dumpsys media.metrics audiotrack,codec
251 // or dumpsys media.metrics audiotrack codec
252
Andy Hung54c73ce2021-03-30 14:25:54 -0700253 static constexpr char result[] =
254 "Recognized parameters:\n"
255 "--all show all records\n"
256 "--clear clear out saved records\n"
257 "--heap show heap usage (top 100)\n"
258 "--help display help\n"
259 "--prefix X process records for component X\n"
260 "--since X X < 0: records from -X seconds in the past\n"
261 " X = 0: ignore\n"
262 " X > 0: records from X seconds since Unix epoch\n"
263 "--unreachable show unreachable memory (leaks)\n";
264 write(fd, result, std::size(result));
Ray Essick35ad27f2017-01-30 14:04:11 -0800265 return NO_ERROR;
Andy Hung709b91e2020-04-04 14:23:36 -0700266 } else if (args[i] == prefixOption) {
267 ++i;
268 if (i < n) {
269 prefix = String8(args[i]).string();
270 }
271 } else if (args[i] == sinceOption) {
272 ++i;
273 if (i < n) {
274 String8 value(args[i]);
275 char *endp;
276 const char *p = value.string();
Andy Hung3ab1b322020-05-18 10:47:31 -0700277 const auto sec = (int64_t)strtoll(p, &endp, 10);
Andy Hung709b91e2020-04-04 14:23:36 -0700278 if (endp == p || *endp != '\0' || sec == 0) {
279 sinceNs = 0;
280 } else if (sec < 0) {
281 sinceNs = systemTime(SYSTEM_TIME_REALTIME) + sec * NANOS_PER_SECOND;
282 } else {
283 sinceNs = sec * NANOS_PER_SECOND;
284 }
285 }
Andy Hung9099a1a2020-04-04 14:23:36 -0700286 } else if (args[i] == unreachableOption) {
287 unreachable = true;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800288 }
289 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700290 std::stringstream result;
Andy Hung17dbaf22019-10-11 14:06:31 -0700291 {
292 std::lock_guard _l(mLock);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800293
Andy Hung17dbaf22019-10-11 14:06:31 -0700294 if (clear) {
Andy Hungc14ee142021-03-10 16:39:02 -0800295 mItemsDiscarded += (int64_t)mItems.size();
Andy Hung17dbaf22019-10-11 14:06:31 -0700296 mItems.clear();
Andy Hung709b91e2020-04-04 14:23:36 -0700297 mAudioAnalytics.clear();
298 } else {
Andy Hung54c73ce2021-03-30 14:25:54 -0700299 result << StringPrintf("Dump of the %s process:\n", kServiceName);
Andy Hung709b91e2020-04-04 14:23:36 -0700300 const char *prefixptr = prefix.size() > 0 ? prefix.c_str() : nullptr;
Andy Hung54c73ce2021-03-30 14:25:54 -0700301 result << dumpHeaders(sinceNs, prefixptr);
302 result << dumpQueue(sinceNs, prefixptr);
Andy Hung709b91e2020-04-04 14:23:36 -0700303
304 // TODO: maybe consider a better way of dumping audio analytics info.
305 const int32_t linesToDump = all ? INT32_MAX : 1000;
306 auto [ dumpString, lines ] = mAudioAnalytics.dump(linesToDump, sinceNs, prefixptr);
Andy Hung54c73ce2021-03-30 14:25:54 -0700307 result << dumpString;
Andy Hung709b91e2020-04-04 14:23:36 -0700308 if (lines == linesToDump) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700309 result << "-- some lines may be truncated --\n";
Andy Hung709b91e2020-04-04 14:23:36 -0700310 }
Andy Hung5be90c82021-03-30 14:30:20 -0700311
312 // Dump the statsd atoms we sent out.
313 result << "Statsd atoms:\n"
314 << mStatsdLog->dumpToString(" " /* prefix */,
315 all ? STATSD_LOG_LINES_MAX : STATSD_LOG_LINES_DUMP);
Andy Hung0f7ad8c2020-01-03 13:24:34 -0800316 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700317 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700318 const std::string str = result.str();
319 write(fd, str.c_str(), str.size());
Andy Hung9099a1a2020-04-04 14:23:36 -0700320
321 // Check heap and unreachable memory outside of lock.
322 if (heap) {
323 dprintf(fd, "\nDumping heap:\n");
324 std::string s = dumpMemoryAddresses(100 /* limit */);
325 write(fd, s.c_str(), s.size());
326 }
327 if (unreachable) {
328 dprintf(fd, "\nDumping unreachable memory:\n");
329 // TODO - should limit be an argument parameter?
330 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
331 write(fd, s.c_str(), s.size());
332 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700333 return NO_ERROR;
334}
335
336// dump headers
Andy Hung54c73ce2021-03-30 14:25:54 -0700337std::string MediaMetricsService::dumpHeaders(int64_t sinceNs, const char* prefix)
Ray Essick92d23b42018-01-29 12:10:30 -0800338{
Andy Hung54c73ce2021-03-30 14:25:54 -0700339 std::stringstream result;
Ray Essickf27e9872019-12-07 06:28:46 -0800340 if (mediametrics::Item::isEnabled()) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700341 result << "Metrics gathering: enabled\n";
Ray Essickb5fac8e2016-12-12 11:33:56 -0800342 } else {
Andy Hung54c73ce2021-03-30 14:25:54 -0700343 result << "Metrics gathering: DISABLED via property\n";
Ray Essickb5fac8e2016-12-12 11:33:56 -0800344 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700345 result << StringPrintf(
Andy Hung17dbaf22019-10-11 14:06:31 -0700346 "Since Boot: Submissions: %lld Accepted: %lld\n",
347 (long long)mItemsSubmitted.load(), (long long)mItemsFinalized);
Andy Hung54c73ce2021-03-30 14:25:54 -0700348 result << StringPrintf(
Andy Hung17dbaf22019-10-11 14:06:31 -0700349 "Records Discarded: %lld (by Count: %lld by Expiration: %lld)\n",
350 (long long)mItemsDiscarded, (long long)mItemsDiscardedCount,
351 (long long)mItemsDiscardedExpire);
Andy Hung709b91e2020-04-04 14:23:36 -0700352 if (prefix != nullptr) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700353 result << "Restricting to prefix " << prefix << "\n";
Andy Hung709b91e2020-04-04 14:23:36 -0700354 }
355 if (sinceNs != 0) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700356 result << "Emitting Queue entries more recent than: " << sinceNs << "\n";
Ray Essickb5fac8e2016-12-12 11:33:56 -0800357 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700358 return result.str();
Ray Essick2e9c63b2017-03-29 15:16:44 -0700359}
360
Andy Hung709b91e2020-04-04 14:23:36 -0700361// TODO: should prefix be a set<string>?
Andy Hung54c73ce2021-03-30 14:25:54 -0700362std::string MediaMetricsService::dumpQueue(int64_t sinceNs, const char* prefix)
Ray Essick92d23b42018-01-29 12:10:30 -0800363{
Ray Essick92d23b42018-01-29 12:10:30 -0800364 if (mItems.empty()) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700365 return "empty\n";
Andy Hung709b91e2020-04-04 14:23:36 -0700366 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700367 std::stringstream result;
Andy Hung709b91e2020-04-04 14:23:36 -0700368 int slot = 0;
369 for (const auto &item : mItems) { // TODO: consider std::lower_bound() on mItems
370 if (item->getTimestamp() < sinceNs) { // sinceNs == 0 means all items shown
371 continue;
Ray Essick3938dc62016-11-01 08:56:56 -0700372 }
Andy Hung709b91e2020-04-04 14:23:36 -0700373 if (prefix != nullptr && !startsWith(item->getKey(), prefix)) {
374 ALOGV("%s: omit '%s', it's not '%s'",
375 __func__, item->getKey().c_str(), prefix);
376 continue;
377 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700378 result << StringPrintf("%5d: %s\n", slot, item->toString().c_str());
Andy Hung709b91e2020-04-04 14:23:36 -0700379 slot++;
Ray Essick3938dc62016-11-01 08:56:56 -0700380 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700381 return result.str();
Ray Essick3938dc62016-11-01 08:56:56 -0700382}
383
384//
385// Our Cheap in-core, non-persistent records management.
Ray Essick3938dc62016-11-01 08:56:56 -0700386
Ray Essick72a436b2018-06-14 15:08:13 -0700387// if item != NULL, it's the item we just inserted
388// true == more items eligible to be recovered
Andy Hungf7c14102020-04-18 14:54:08 -0700389bool MediaMetricsService::expirations(const std::shared_ptr<const mediametrics::Item>& item)
Ray Essick92d23b42018-01-29 12:10:30 -0800390{
Ray Essick72a436b2018-06-14 15:08:13 -0700391 bool more = false;
Ray Essicke5db6db2017-11-10 15:54:32 -0800392
Andy Hung17dbaf22019-10-11 14:06:31 -0700393 // check queue size
394 size_t overlimit = 0;
395 if (mMaxRecords > 0 && mItems.size() > mMaxRecords) {
396 overlimit = mItems.size() - mMaxRecords;
397 if (overlimit > mMaxRecordsExpiredAtOnce) {
398 more = true;
399 overlimit = mMaxRecordsExpiredAtOnce;
Ray Essickf65f4212017-08-31 11:41:19 -0700400 }
401 }
402
Andy Hung17dbaf22019-10-11 14:06:31 -0700403 // check queue times
404 size_t expired = 0;
405 if (!more && mMaxRecordAgeNs > 0) {
406 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
407 // we check one at a time, skip search would be more efficient.
408 size_t i = overlimit;
409 for (; i < mItems.size(); ++i) {
410 auto &oitem = mItems[i];
Ray Essickf65f4212017-08-31 11:41:19 -0700411 nsecs_t when = oitem->getTimestamp();
Andy Hung82a074b2019-12-03 14:16:45 -0800412 if (oitem.get() == item.get()) {
Ray Essicke5db6db2017-11-10 15:54:32 -0800413 break;
414 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700415 if (now > when && (now - when) <= mMaxRecordAgeNs) {
Andy Hunged416da2020-03-05 18:42:55 -0800416 break; // Note SYSTEM_TIME_REALTIME may not be monotonic.
Ray Essickf65f4212017-08-31 11:41:19 -0700417 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700418 if (i >= mMaxRecordsExpiredAtOnce) {
Ray Essick72a436b2018-06-14 15:08:13 -0700419 // this represents "one too many"; tell caller there are
420 // more to be reclaimed.
421 more = true;
422 break;
423 }
Ray Essick3938dc62016-11-01 08:56:56 -0700424 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700425 expired = i - overlimit;
Ray Essick3938dc62016-11-01 08:56:56 -0700426 }
Ray Essick72a436b2018-06-14 15:08:13 -0700427
Andy Hung17dbaf22019-10-11 14:06:31 -0700428 if (const size_t toErase = overlimit + expired;
429 toErase > 0) {
Andy Hungc14ee142021-03-10 16:39:02 -0800430 mItemsDiscardedCount += (int64_t)overlimit;
431 mItemsDiscardedExpire += (int64_t)expired;
432 mItemsDiscarded += (int64_t)toErase;
433 mItems.erase(mItems.begin(), mItems.begin() + (ptrdiff_t)toErase); // erase from front
Andy Hung17dbaf22019-10-11 14:06:31 -0700434 }
Ray Essick72a436b2018-06-14 15:08:13 -0700435 return more;
436}
437
Ray Essickf27e9872019-12-07 06:28:46 -0800438void MediaMetricsService::processExpirations()
Ray Essick72a436b2018-06-14 15:08:13 -0700439{
440 bool more;
441 do {
442 sleep(1);
Andy Hung17dbaf22019-10-11 14:06:31 -0700443 std::lock_guard _l(mLock);
Andy Hungf7c14102020-04-18 14:54:08 -0700444 more = expirations(nullptr);
Ray Essick72a436b2018-06-14 15:08:13 -0700445 } while (more);
Ray Essick72a436b2018-06-14 15:08:13 -0700446}
447
Ray Essickf27e9872019-12-07 06:28:46 -0800448void MediaMetricsService::saveItem(const std::shared_ptr<const mediametrics::Item>& item)
Ray Essick72a436b2018-06-14 15:08:13 -0700449{
Andy Hung17dbaf22019-10-11 14:06:31 -0700450 std::lock_guard _l(mLock);
451 // we assume the items are roughly in time order.
452 mItems.emplace_back(item);
Robert Shih2e15aed2021-03-16 18:30:35 -0700453 if (isPullable(item->getKey())) {
454 registerStatsdCallbacksIfNeeded();
455 mPullableItems[item->getKey()].emplace_back(item);
456 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700457 ++mItemsFinalized;
Andy Hungf7c14102020-04-18 14:54:08 -0700458 if (expirations(item)
Andy Hung17dbaf22019-10-11 14:06:31 -0700459 && (!mExpireFuture.valid()
460 || mExpireFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready)) {
461 mExpireFuture = std::async(std::launch::async, [this] { processExpirations(); });
Ray Essick72a436b2018-06-14 15:08:13 -0700462 }
Ray Essick3938dc62016-11-01 08:56:56 -0700463}
464
Andy Hung17dbaf22019-10-11 14:06:31 -0700465/* static */
Ray Essickf27e9872019-12-07 06:28:46 -0800466bool MediaMetricsService::isContentValid(const mediametrics::Item *item, bool isTrusted)
Ray Essickd38e1742017-01-23 15:17:06 -0800467{
Andy Hung17dbaf22019-10-11 14:06:31 -0700468 if (isTrusted) return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800469 // untrusted uids can only send us a limited set of keys
Andy Hung17dbaf22019-10-11 14:06:31 -0700470 const std::string &key = item->getKey();
Andy Hung06f3aba2019-12-03 16:36:42 -0800471 if (startsWith(key, "audio.")) return true;
Edwin Wong8d188352020-02-11 11:59:34 -0800472 if (startsWith(key, "drm.vendor.")) return true;
473 // the list of allowedKey uses statsd_handlers
474 // in iface_statsd.cpp as reference
475 // drmmanager is from a trusted uid, therefore not needed here
Andy Hung17dbaf22019-10-11 14:06:31 -0700476 for (const char *allowedKey : {
Andy Hung06f3aba2019-12-03 16:36:42 -0800477 // legacy audio
Andy Hung17dbaf22019-10-11 14:06:31 -0700478 "audiopolicy",
479 "audiorecord",
480 "audiothread",
481 "audiotrack",
Andy Hung06f3aba2019-12-03 16:36:42 -0800482 // other media
Andy Hung17dbaf22019-10-11 14:06:31 -0700483 "codec",
484 "extractor",
Edwin Wong8d188352020-02-11 11:59:34 -0800485 "mediadrm",
Santiago Seifert49fb4522020-08-07 13:48:45 +0100486 "mediaparser",
Andy Hung17dbaf22019-10-11 14:06:31 -0700487 "nuplayer",
488 }) {
489 if (key == allowedKey) {
490 return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800491 }
492 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700493 ALOGD("%s: invalid key: %s", __func__, item->toString().c_str());
Ray Essick3938dc62016-11-01 08:56:56 -0700494 return false;
495}
496
Andy Hung17dbaf22019-10-11 14:06:31 -0700497// are we rate limited, normally false
Ray Essickf27e9872019-12-07 06:28:46 -0800498bool MediaMetricsService::isRateLimited(mediametrics::Item *) const
Andy Hung17dbaf22019-10-11 14:06:31 -0700499{
500 return false;
501}
502
Robert Shih2e15aed2021-03-16 18:30:35 -0700503void MediaMetricsService::registerStatsdCallbacksIfNeeded()
504{
505 if (mStatsdRegistered.test_and_set()) {
506 return;
507 }
508 auto tag = android::util::MEDIA_DRM_ACTIVITY_INFO;
509 auto cb = MediaMetricsService::pullAtomCallback;
510 AStatsManager_setPullAtomCallback(tag, /* metadata */ nullptr, cb, this);
511}
512
513/* static */
514bool MediaMetricsService::isPullable(const std::string &key)
515{
516 static const std::set<std::string> pullableKeys{
517 "mediadrm",
518 };
519 return pullableKeys.count(key);
520}
521
522/* static */
523std::string MediaMetricsService::atomTagToKey(int32_t atomTag)
524{
525 switch (atomTag) {
526 case android::util::MEDIA_DRM_ACTIVITY_INFO:
527 return "mediadrm";
528 }
529 return {};
530}
531
532/* static */
533AStatsManager_PullAtomCallbackReturn MediaMetricsService::pullAtomCallback(
534 int32_t atomTag, AStatsEventList* data, void* cookie)
535{
536 MediaMetricsService* svc = reinterpret_cast<MediaMetricsService*>(cookie);
537 return svc->pullItems(atomTag, data);
538}
539
540AStatsManager_PullAtomCallbackReturn MediaMetricsService::pullItems(
541 int32_t atomTag, AStatsEventList* data)
542{
543 const std::string key(atomTagToKey(atomTag));
544 if (key.empty()) {
545 return AStatsManager_PULL_SKIP;
546 }
547 std::lock_guard _l(mLock);
548 for (auto &item : mPullableItems[key]) {
549 if (const auto sitem = item.lock()) {
550 dump2Statsd(sitem, data);
551 }
552 }
553 mPullableItems[key].clear();
554 return AStatsManager_PULL_SUCCESS;
555}
Ray Essick3938dc62016-11-01 08:56:56 -0700556} // namespace android