blob: bfc722e91ca2a731fc91e42d8b98d39c0c16e4cd [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 Hung17dbaf22019-10-11 14:06:31 -070026#include <android/content/pm/IPackageManagerNative.h> // package info
Andy Hung55aaf522019-12-03 15:07:51 -080027#include <audio_utils/clock.h> // clock conversions
Andy Hung17dbaf22019-10-11 14:06:31 -070028#include <binder/IPCThreadState.h> // get calling uid
Andy Hung49ca44e2020-11-10 22:14:58 -080029#include <binder/IServiceManager.h> // checkCallingPermission
Andy Hung17dbaf22019-10-11 14:06:31 -070030#include <cutils/properties.h> // for property_get
Andy Hung9099a1a2020-04-04 14:23:36 -070031#include <mediautils/MemoryLeakTrackUtil.h>
32#include <memunreachable/memunreachable.h>
Andy Hung17dbaf22019-10-11 14:06:31 -070033#include <private/android_filesystem_config.h> // UID
Robert Shih2e15aed2021-03-16 18:30:35 -070034#include <statslog.h>
35
36#include <set>
Andy Hung17dbaf22019-10-11 14:06:31 -070037
Ray Essick3938dc62016-11-01 08:56:56 -070038namespace android {
39
Andy Hung3ab1b322020-05-18 10:47:31 -070040using mediametrics::Item;
41using mediametrics::startsWith;
Andy Hung1efc9c62019-12-03 13:43:33 -080042
Ray Essickf65f4212017-08-31 11:41:19 -070043// individual records kept in memory: age or count
Ray Essick72a436b2018-06-14 15:08:13 -070044// age: <= 28 hours (1 1/6 days)
Ray Essickf65f4212017-08-31 11:41:19 -070045// count: hard limit of # records
46// (0 for either of these disables that threshold)
Ray Essick72a436b2018-06-14 15:08:13 -070047//
Andy Hung17dbaf22019-10-11 14:06:31 -070048static constexpr nsecs_t kMaxRecordAgeNs = 28 * 3600 * NANOS_PER_SECOND;
Ray Essick23f4d6c2019-06-20 10:16:37 -070049// 2019/6: average daily per device is currently 375-ish;
50// setting this to 2000 is large enough to catch most devices
51// we'll lose some data on very very media-active devices, but only for
52// the gms collection; statsd will have already covered those for us.
53// This also retains enough information to help with bugreports
Andy Hung17dbaf22019-10-11 14:06:31 -070054static constexpr size_t kMaxRecords = 2000;
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{
Andy Hung3ab1b322020-05-18 10:47:31 -070072 if (strchr(package.c_str(), '.') == nullptr) {
Andy Hunga85efab2019-12-23 11:41:29 -080073 return false; // not of form 'com.whatever...'; assume internal and ok
74 } else if (strncmp(package.c_str(), "android.", 8) == 0) {
75 return false; // android.* packages are assumed fine
76 } else if (strncmp(installer.c_str(), "com.android.", 12) == 0) {
77 return false; // from play store
78 } else if (strncmp(installer.c_str(), "com.google.", 11) == 0) {
79 return false; // some google source
80 } else if (strcmp(installer.c_str(), "preload") == 0) {
81 return false; // preloads
82 } else {
83 return true; // we're not sure where it came from, use uid only.
84 }
85}
86
Andy Hungce9b6632020-04-28 20:15:17 -070087/* static */
88std::pair<std::string, int64_t>
89MediaMetricsService::getSanitizedPackageNameAndVersionCode(uid_t uid) {
90 // Meyer's singleton, initialized on first access.
91 // mUidInfo is locked internally.
92 static mediautils::UidInfo uidInfo;
93
94 // get info.
95 mediautils::UidInfo::Info info = uidInfo.getInfo(uid);
96 if (useUidForPackage(info.package, info.installer)) {
97 return { std::to_string(uid), /* versionCode */ 0 };
98 } else {
99 return { info.package, info.versionCode };
100 }
101}
102
Ray Essickf27e9872019-12-07 06:28:46 -0800103MediaMetricsService::MediaMetricsService()
Ray Essick2e9c63b2017-03-29 15:16:44 -0700104 : mMaxRecords(kMaxRecords),
Ray Essickf65f4212017-08-31 11:41:19 -0700105 mMaxRecordAgeNs(kMaxRecordAgeNs),
Andy Hung3b4c1f02020-01-23 18:58:32 -0800106 mMaxRecordsExpiredAtOnce(kMaxExpiredAtOnce)
Andy Hung17dbaf22019-10-11 14:06:31 -0700107{
108 ALOGD("%s", __func__);
Ray Essick3938dc62016-11-01 08:56:56 -0700109}
110
Ray Essickf27e9872019-12-07 06:28:46 -0800111MediaMetricsService::~MediaMetricsService()
Andy Hung17dbaf22019-10-11 14:06:31 -0700112{
113 ALOGD("%s", __func__);
114 // the class destructor clears anyhow, but we enforce clearing items first.
Andy Hungc14ee142021-03-10 16:39:02 -0800115 mItemsDiscarded += (int64_t)mItems.size();
Andy Hung17dbaf22019-10-11 14:06:31 -0700116 mItems.clear();
Ray Essick3938dc62016-11-01 08:56:56 -0700117}
118
Ray Essickf27e9872019-12-07 06:28:46 -0800119status_t MediaMetricsService::submitInternal(mediametrics::Item *item, bool release)
Ray Essick92d23b42018-01-29 12:10:30 -0800120{
Andy Hung55aaf522019-12-03 15:07:51 -0800121 // calling PID is 0 for one-way calls.
122 const pid_t pid = IPCThreadState::self()->getCallingPid();
123 const pid_t pid_given = item->getPid();
124 const uid_t uid = IPCThreadState::self()->getCallingUid();
125 const uid_t uid_given = item->getUid();
Ray Essickd38e1742017-01-23 15:17:06 -0800126
Andy Hung55aaf522019-12-03 15:07:51 -0800127 //ALOGD("%s: caller pid=%d uid=%d, item pid=%d uid=%d", __func__,
128 // (int)pid, (int)uid, (int) pid_given, (int)uid_given);
Ray Essickd38e1742017-01-23 15:17:06 -0800129
Andy Hung17dbaf22019-10-11 14:06:31 -0700130 bool isTrusted;
131 switch (uid) {
Andy Hung55aaf522019-12-03 15:07:51 -0800132 case AID_AUDIOSERVER:
133 case AID_BLUETOOTH:
134 case AID_CAMERA:
Andy Hung17dbaf22019-10-11 14:06:31 -0700135 case AID_DRM:
136 case AID_MEDIA:
137 case AID_MEDIA_CODEC:
138 case AID_MEDIA_EX:
139 case AID_MEDIA_DRM:
Andy Hung5d3f2d12020-03-04 19:55:03 -0800140 // case AID_SHELL: // DEBUG ONLY - used for mediametrics_tests to add new keys
Andy Hung55aaf522019-12-03 15:07:51 -0800141 case AID_SYSTEM:
Andy Hung17dbaf22019-10-11 14:06:31 -0700142 // trusted source, only override default values
143 isTrusted = true;
Andy Hung55aaf522019-12-03 15:07:51 -0800144 if (uid_given == (uid_t)-1) {
Ray Essickd38e1742017-01-23 15:17:06 -0800145 item->setUid(uid);
Andy Hung17dbaf22019-10-11 14:06:31 -0700146 }
Andy Hung55aaf522019-12-03 15:07:51 -0800147 if (pid_given == (pid_t)-1) {
148 item->setPid(pid); // if one-way then this is 0.
Andy Hung17dbaf22019-10-11 14:06:31 -0700149 }
150 break;
151 default:
152 isTrusted = false;
Andy Hung55aaf522019-12-03 15:07:51 -0800153 item->setPid(pid); // always use calling pid, if one-way then this is 0.
Andy Hung17dbaf22019-10-11 14:06:31 -0700154 item->setUid(uid);
155 break;
Ray Essickd38e1742017-01-23 15:17:06 -0800156 }
157
Andy Hunga85efab2019-12-23 11:41:29 -0800158 // Overwrite package name and version if the caller was untrusted or empty
159 if (!isTrusted || item->getPkgName().empty()) {
Andy Hung3ab1b322020-05-18 10:47:31 -0700160 const uid_t uidItem = item->getUid();
Andy Hungce9b6632020-04-28 20:15:17 -0700161 const auto [ pkgName, version ] =
Andy Hung3ab1b322020-05-18 10:47:31 -0700162 MediaMetricsService::getSanitizedPackageNameAndVersionCode(uidItem);
Andy Hungce9b6632020-04-28 20:15:17 -0700163 item->setPkgName(pkgName);
164 item->setPkgVersionCode(version);
Adam Stone21c72122017-09-05 19:02:06 -0700165 }
166
Andy Hung5d3f2d12020-03-04 19:55:03 -0800167 ALOGV("%s: isTrusted:%d given uid %d; sanitized uid: %d sanitized pkg: %s "
Andy Hung17dbaf22019-10-11 14:06:31 -0700168 "sanitized pkg version: %lld",
169 __func__,
Andy Hung5d3f2d12020-03-04 19:55:03 -0800170 (int)isTrusted,
Adam Stone21c72122017-09-05 19:02:06 -0700171 uid_given, item->getUid(),
172 item->getPkgName().c_str(),
Andy Hung17dbaf22019-10-11 14:06:31 -0700173 (long long)item->getPkgVersionCode());
Ray Essick3938dc62016-11-01 08:56:56 -0700174
175 mItemsSubmitted++;
176
177 // validate the record; we discard if we don't like it
Andy Hung17dbaf22019-10-11 14:06:31 -0700178 if (isContentValid(item, isTrusted) == false) {
Andy Hunga87e69c2019-10-18 10:07:40 -0700179 if (release) delete item;
180 return PERMISSION_DENIED;
Ray Essick3938dc62016-11-01 08:56:56 -0700181 }
182
Ray Essick92d23b42018-01-29 12:10:30 -0800183 // XXX: if we have a sessionid in the new record, look to make
Ray Essick3938dc62016-11-01 08:56:56 -0700184 // sure it doesn't appear in the finalized list.
Ray Essick3938dc62016-11-01 08:56:56 -0700185
Ray Essick92d23b42018-01-29 12:10:30 -0800186 if (item->count() == 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700187 ALOGV("%s: dropping empty record...", __func__);
Andy Hunga87e69c2019-10-18 10:07:40 -0700188 if (release) delete item;
189 return BAD_VALUE;
Ray Essick3938dc62016-11-01 08:56:56 -0700190 }
Ray Essick92d23b42018-01-29 12:10:30 -0800191
Andy Hung55aaf522019-12-03 15:07:51 -0800192 if (!isTrusted || item->getTimestamp() == 0) {
Muhammad Qureshi087b37c2020-06-16 16:37:36 -0700193 // Statsd logs two times for events: ElapsedRealTimeNs (BOOTTIME) and
Andy Hung3b4c1f02020-01-23 18:58:32 -0800194 // WallClockTimeNs (REALTIME), but currently logs REALTIME to cloud.
Andy Hung55aaf522019-12-03 15:07:51 -0800195 //
Andy Hung3b4c1f02020-01-23 18:58:32 -0800196 // For consistency and correlation with other logging mechanisms
197 // we use REALTIME here.
198 const int64_t now = systemTime(SYSTEM_TIME_REALTIME);
Andy Hung55aaf522019-12-03 15:07:51 -0800199 item->setTimestamp(now);
200 }
201
Andy Hung82a074b2019-12-03 14:16:45 -0800202 // now attach either the item or its dup to a const shared pointer
Ray Essickf27e9872019-12-07 06:28:46 -0800203 std::shared_ptr<const mediametrics::Item> sitem(release ? item : item->dup());
Ray Essick6ce27e52019-02-15 10:58:05 -0800204
Andy Hung06f3aba2019-12-03 16:36:42 -0800205 (void)mAudioAnalytics.submit(sitem, isTrusted);
206
Andy Hung82a074b2019-12-03 14:16:45 -0800207 (void)dump2Statsd(sitem); // failure should be logged in function.
208 saveItem(sitem);
Andy Hunga87e69c2019-10-18 10:07:40 -0700209 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700210}
211
Ray Essickf27e9872019-12-07 06:28:46 -0800212status_t MediaMetricsService::dump(int fd, const Vector<String16>& args)
Ray Essick3938dc62016-11-01 08:56:56 -0700213{
Ray Essick3938dc62016-11-01 08:56:56 -0700214 String8 result;
215
216 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700217 result.appendFormat("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());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800221 write(fd, result.string(), result.size());
222 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
Ray Essick35ad27f2017-01-30 14:04:11 -0800253 result.append("Recognized parameters:\n");
Andy Hung709b91e2020-04-04 14:23:36 -0700254 result.append("--all show all records\n");
255 result.append("--clear clear out saved records\n");
256 result.append("--heap show heap usage (top 100)\n");
257 result.append("--help display help\n");
258 result.append("--prefix X process records for component X\n");
259 result.append("--since X X < 0: records from -X seconds in the past\n");
260 result.append(" X = 0: ignore\n");
261 result.append(" X > 0: records from X seconds since Unix epoch\n");
262 result.append("--unreachable show unreachable memory (leaks)\n");
Ray Essick35ad27f2017-01-30 14:04:11 -0800263 write(fd, result.string(), result.size());
264 return NO_ERROR;
Andy Hung709b91e2020-04-04 14:23:36 -0700265 } else if (args[i] == prefixOption) {
266 ++i;
267 if (i < n) {
268 prefix = String8(args[i]).string();
269 }
270 } else if (args[i] == sinceOption) {
271 ++i;
272 if (i < n) {
273 String8 value(args[i]);
274 char *endp;
275 const char *p = value.string();
Andy Hung3ab1b322020-05-18 10:47:31 -0700276 const auto sec = (int64_t)strtoll(p, &endp, 10);
Andy Hung709b91e2020-04-04 14:23:36 -0700277 if (endp == p || *endp != '\0' || sec == 0) {
278 sinceNs = 0;
279 } else if (sec < 0) {
280 sinceNs = systemTime(SYSTEM_TIME_REALTIME) + sec * NANOS_PER_SECOND;
281 } else {
282 sinceNs = sec * NANOS_PER_SECOND;
283 }
284 }
Andy Hung9099a1a2020-04-04 14:23:36 -0700285 } else if (args[i] == unreachableOption) {
286 unreachable = true;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800287 }
288 }
289
Andy Hung17dbaf22019-10-11 14:06:31 -0700290 {
291 std::lock_guard _l(mLock);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800292
Andy Hung17dbaf22019-10-11 14:06:31 -0700293 if (clear) {
Andy Hungc14ee142021-03-10 16:39:02 -0800294 mItemsDiscarded += (int64_t)mItems.size();
Andy Hung17dbaf22019-10-11 14:06:31 -0700295 mItems.clear();
Andy Hung709b91e2020-04-04 14:23:36 -0700296 mAudioAnalytics.clear();
297 } else {
298 result.appendFormat("Dump of the %s process:\n", kServiceName);
299 const char *prefixptr = prefix.size() > 0 ? prefix.c_str() : nullptr;
Andy Hungf7c14102020-04-18 14:54:08 -0700300 dumpHeaders(result, sinceNs, prefixptr);
301 dumpQueue(result, sinceNs, prefixptr);
Andy Hung709b91e2020-04-04 14:23:36 -0700302
303 // TODO: maybe consider a better way of dumping audio analytics info.
304 const int32_t linesToDump = all ? INT32_MAX : 1000;
305 auto [ dumpString, lines ] = mAudioAnalytics.dump(linesToDump, sinceNs, prefixptr);
306 result.append(dumpString.c_str());
307 if (lines == linesToDump) {
308 result.append("-- some lines may be truncated --\n");
309 }
Andy Hung0f7ad8c2020-01-03 13:24:34 -0800310 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700311 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700312 write(fd, result.string(), result.size());
Andy Hung9099a1a2020-04-04 14:23:36 -0700313
314 // Check heap and unreachable memory outside of lock.
315 if (heap) {
316 dprintf(fd, "\nDumping heap:\n");
317 std::string s = dumpMemoryAddresses(100 /* limit */);
318 write(fd, s.c_str(), s.size());
319 }
320 if (unreachable) {
321 dprintf(fd, "\nDumping unreachable memory:\n");
322 // TODO - should limit be an argument parameter?
323 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
324 write(fd, s.c_str(), s.size());
325 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700326 return NO_ERROR;
327}
328
329// dump headers
Andy Hungf7c14102020-04-18 14:54:08 -0700330void MediaMetricsService::dumpHeaders(String8 &result, int64_t sinceNs, const char* prefix)
Ray Essick92d23b42018-01-29 12:10:30 -0800331{
Ray Essickf27e9872019-12-07 06:28:46 -0800332 if (mediametrics::Item::isEnabled()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700333 result.append("Metrics gathering: enabled\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800334 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700335 result.append("Metrics gathering: DISABLED via property\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800336 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700337 result.appendFormat(
338 "Since Boot: Submissions: %lld Accepted: %lld\n",
339 (long long)mItemsSubmitted.load(), (long long)mItemsFinalized);
340 result.appendFormat(
341 "Records Discarded: %lld (by Count: %lld by Expiration: %lld)\n",
342 (long long)mItemsDiscarded, (long long)mItemsDiscardedCount,
343 (long long)mItemsDiscardedExpire);
Andy Hung709b91e2020-04-04 14:23:36 -0700344 if (prefix != nullptr) {
345 result.appendFormat("Restricting to prefix %s", prefix);
346 }
347 if (sinceNs != 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700348 result.appendFormat(
349 "Emitting Queue entries more recent than: %lld\n",
Andy Hung709b91e2020-04-04 14:23:36 -0700350 (long long)sinceNs);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800351 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700352}
353
Andy Hung709b91e2020-04-04 14:23:36 -0700354// TODO: should prefix be a set<string>?
Andy Hungf7c14102020-04-18 14:54:08 -0700355void MediaMetricsService::dumpQueue(String8 &result, int64_t sinceNs, const char* prefix)
Ray Essick92d23b42018-01-29 12:10:30 -0800356{
Ray Essick92d23b42018-01-29 12:10:30 -0800357 if (mItems.empty()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700358 result.append("empty\n");
Andy Hung709b91e2020-04-04 14:23:36 -0700359 return;
360 }
361
362 int slot = 0;
363 for (const auto &item : mItems) { // TODO: consider std::lower_bound() on mItems
364 if (item->getTimestamp() < sinceNs) { // sinceNs == 0 means all items shown
365 continue;
Ray Essick3938dc62016-11-01 08:56:56 -0700366 }
Andy Hung709b91e2020-04-04 14:23:36 -0700367 if (prefix != nullptr && !startsWith(item->getKey(), prefix)) {
368 ALOGV("%s: omit '%s', it's not '%s'",
369 __func__, item->getKey().c_str(), prefix);
370 continue;
371 }
372 result.appendFormat("%5d: %s\n", slot, item->toString().c_str());
373 slot++;
Ray Essick3938dc62016-11-01 08:56:56 -0700374 }
Ray Essick3938dc62016-11-01 08:56:56 -0700375}
376
377//
378// Our Cheap in-core, non-persistent records management.
Ray Essick3938dc62016-11-01 08:56:56 -0700379
Ray Essick72a436b2018-06-14 15:08:13 -0700380// if item != NULL, it's the item we just inserted
381// true == more items eligible to be recovered
Andy Hungf7c14102020-04-18 14:54:08 -0700382bool MediaMetricsService::expirations(const std::shared_ptr<const mediametrics::Item>& item)
Ray Essick92d23b42018-01-29 12:10:30 -0800383{
Ray Essick72a436b2018-06-14 15:08:13 -0700384 bool more = false;
Ray Essicke5db6db2017-11-10 15:54:32 -0800385
Andy Hung17dbaf22019-10-11 14:06:31 -0700386 // check queue size
387 size_t overlimit = 0;
388 if (mMaxRecords > 0 && mItems.size() > mMaxRecords) {
389 overlimit = mItems.size() - mMaxRecords;
390 if (overlimit > mMaxRecordsExpiredAtOnce) {
391 more = true;
392 overlimit = mMaxRecordsExpiredAtOnce;
Ray Essickf65f4212017-08-31 11:41:19 -0700393 }
394 }
395
Andy Hung17dbaf22019-10-11 14:06:31 -0700396 // check queue times
397 size_t expired = 0;
398 if (!more && mMaxRecordAgeNs > 0) {
399 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
400 // we check one at a time, skip search would be more efficient.
401 size_t i = overlimit;
402 for (; i < mItems.size(); ++i) {
403 auto &oitem = mItems[i];
Ray Essickf65f4212017-08-31 11:41:19 -0700404 nsecs_t when = oitem->getTimestamp();
Andy Hung82a074b2019-12-03 14:16:45 -0800405 if (oitem.get() == item.get()) {
Ray Essicke5db6db2017-11-10 15:54:32 -0800406 break;
407 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700408 if (now > when && (now - when) <= mMaxRecordAgeNs) {
Andy Hunged416da2020-03-05 18:42:55 -0800409 break; // Note SYSTEM_TIME_REALTIME may not be monotonic.
Ray Essickf65f4212017-08-31 11:41:19 -0700410 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700411 if (i >= mMaxRecordsExpiredAtOnce) {
Ray Essick72a436b2018-06-14 15:08:13 -0700412 // this represents "one too many"; tell caller there are
413 // more to be reclaimed.
414 more = true;
415 break;
416 }
Ray Essick3938dc62016-11-01 08:56:56 -0700417 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700418 expired = i - overlimit;
Ray Essick3938dc62016-11-01 08:56:56 -0700419 }
Ray Essick72a436b2018-06-14 15:08:13 -0700420
Andy Hung17dbaf22019-10-11 14:06:31 -0700421 if (const size_t toErase = overlimit + expired;
422 toErase > 0) {
Andy Hungc14ee142021-03-10 16:39:02 -0800423 mItemsDiscardedCount += (int64_t)overlimit;
424 mItemsDiscardedExpire += (int64_t)expired;
425 mItemsDiscarded += (int64_t)toErase;
426 mItems.erase(mItems.begin(), mItems.begin() + (ptrdiff_t)toErase); // erase from front
Andy Hung17dbaf22019-10-11 14:06:31 -0700427 }
Ray Essick72a436b2018-06-14 15:08:13 -0700428 return more;
429}
430
Ray Essickf27e9872019-12-07 06:28:46 -0800431void MediaMetricsService::processExpirations()
Ray Essick72a436b2018-06-14 15:08:13 -0700432{
433 bool more;
434 do {
435 sleep(1);
Andy Hung17dbaf22019-10-11 14:06:31 -0700436 std::lock_guard _l(mLock);
Andy Hungf7c14102020-04-18 14:54:08 -0700437 more = expirations(nullptr);
Ray Essick72a436b2018-06-14 15:08:13 -0700438 } while (more);
Ray Essick72a436b2018-06-14 15:08:13 -0700439}
440
Ray Essickf27e9872019-12-07 06:28:46 -0800441void MediaMetricsService::saveItem(const std::shared_ptr<const mediametrics::Item>& item)
Ray Essick72a436b2018-06-14 15:08:13 -0700442{
Andy Hung17dbaf22019-10-11 14:06:31 -0700443 std::lock_guard _l(mLock);
444 // we assume the items are roughly in time order.
445 mItems.emplace_back(item);
Robert Shih2e15aed2021-03-16 18:30:35 -0700446 if (isPullable(item->getKey())) {
447 registerStatsdCallbacksIfNeeded();
448 mPullableItems[item->getKey()].emplace_back(item);
449 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700450 ++mItemsFinalized;
Andy Hungf7c14102020-04-18 14:54:08 -0700451 if (expirations(item)
Andy Hung17dbaf22019-10-11 14:06:31 -0700452 && (!mExpireFuture.valid()
453 || mExpireFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready)) {
454 mExpireFuture = std::async(std::launch::async, [this] { processExpirations(); });
Ray Essick72a436b2018-06-14 15:08:13 -0700455 }
Ray Essick3938dc62016-11-01 08:56:56 -0700456}
457
Andy Hung17dbaf22019-10-11 14:06:31 -0700458/* static */
Ray Essickf27e9872019-12-07 06:28:46 -0800459bool MediaMetricsService::isContentValid(const mediametrics::Item *item, bool isTrusted)
Ray Essickd38e1742017-01-23 15:17:06 -0800460{
Andy Hung17dbaf22019-10-11 14:06:31 -0700461 if (isTrusted) return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800462 // untrusted uids can only send us a limited set of keys
Andy Hung17dbaf22019-10-11 14:06:31 -0700463 const std::string &key = item->getKey();
Andy Hung06f3aba2019-12-03 16:36:42 -0800464 if (startsWith(key, "audio.")) return true;
Edwin Wong8d188352020-02-11 11:59:34 -0800465 if (startsWith(key, "drm.vendor.")) return true;
466 // the list of allowedKey uses statsd_handlers
467 // in iface_statsd.cpp as reference
468 // drmmanager is from a trusted uid, therefore not needed here
Andy Hung17dbaf22019-10-11 14:06:31 -0700469 for (const char *allowedKey : {
Andy Hung06f3aba2019-12-03 16:36:42 -0800470 // legacy audio
Andy Hung17dbaf22019-10-11 14:06:31 -0700471 "audiopolicy",
472 "audiorecord",
473 "audiothread",
474 "audiotrack",
Andy Hung06f3aba2019-12-03 16:36:42 -0800475 // other media
Andy Hung17dbaf22019-10-11 14:06:31 -0700476 "codec",
477 "extractor",
Edwin Wong8d188352020-02-11 11:59:34 -0800478 "mediadrm",
Santiago Seifert49fb4522020-08-07 13:48:45 +0100479 "mediaparser",
Andy Hung17dbaf22019-10-11 14:06:31 -0700480 "nuplayer",
481 }) {
482 if (key == allowedKey) {
483 return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800484 }
485 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700486 ALOGD("%s: invalid key: %s", __func__, item->toString().c_str());
Ray Essick3938dc62016-11-01 08:56:56 -0700487 return false;
488}
489
Andy Hung17dbaf22019-10-11 14:06:31 -0700490// are we rate limited, normally false
Ray Essickf27e9872019-12-07 06:28:46 -0800491bool MediaMetricsService::isRateLimited(mediametrics::Item *) const
Andy Hung17dbaf22019-10-11 14:06:31 -0700492{
493 return false;
494}
495
Robert Shih2e15aed2021-03-16 18:30:35 -0700496void MediaMetricsService::registerStatsdCallbacksIfNeeded()
497{
498 if (mStatsdRegistered.test_and_set()) {
499 return;
500 }
501 auto tag = android::util::MEDIA_DRM_ACTIVITY_INFO;
502 auto cb = MediaMetricsService::pullAtomCallback;
503 AStatsManager_setPullAtomCallback(tag, /* metadata */ nullptr, cb, this);
504}
505
506/* static */
507bool MediaMetricsService::isPullable(const std::string &key)
508{
509 static const std::set<std::string> pullableKeys{
510 "mediadrm",
511 };
512 return pullableKeys.count(key);
513}
514
515/* static */
516std::string MediaMetricsService::atomTagToKey(int32_t atomTag)
517{
518 switch (atomTag) {
519 case android::util::MEDIA_DRM_ACTIVITY_INFO:
520 return "mediadrm";
521 }
522 return {};
523}
524
525/* static */
526AStatsManager_PullAtomCallbackReturn MediaMetricsService::pullAtomCallback(
527 int32_t atomTag, AStatsEventList* data, void* cookie)
528{
529 MediaMetricsService* svc = reinterpret_cast<MediaMetricsService*>(cookie);
530 return svc->pullItems(atomTag, data);
531}
532
533AStatsManager_PullAtomCallbackReturn MediaMetricsService::pullItems(
534 int32_t atomTag, AStatsEventList* data)
535{
536 const std::string key(atomTagToKey(atomTag));
537 if (key.empty()) {
538 return AStatsManager_PULL_SKIP;
539 }
540 std::lock_guard _l(mLock);
541 for (auto &item : mPullableItems[key]) {
542 if (const auto sitem = item.lock()) {
543 dump2Statsd(sitem, data);
544 }
545 }
546 mPullableItems[key].clear();
547 return AStatsManager_PULL_SUCCESS;
548}
Ray Essick3938dc62016-11-01 08:56:56 -0700549} // namespace android