blob: 7ee731e8b377d7a1e46c98c71a8c48bb94bee4ef [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 Hung82a074b2019-12-03 14:16:45 -0800209 (void)dump2Statsd(sitem); // failure should be logged in function.
210 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 Hung0f7ad8c2020-01-03 13:24:34 -0800311 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700312 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700313 const std::string str = result.str();
314 write(fd, str.c_str(), str.size());
Andy Hung9099a1a2020-04-04 14:23:36 -0700315
316 // Check heap and unreachable memory outside of lock.
317 if (heap) {
318 dprintf(fd, "\nDumping heap:\n");
319 std::string s = dumpMemoryAddresses(100 /* limit */);
320 write(fd, s.c_str(), s.size());
321 }
322 if (unreachable) {
323 dprintf(fd, "\nDumping unreachable memory:\n");
324 // TODO - should limit be an argument parameter?
325 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
326 write(fd, s.c_str(), s.size());
327 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700328 return NO_ERROR;
329}
330
331// dump headers
Andy Hung54c73ce2021-03-30 14:25:54 -0700332std::string MediaMetricsService::dumpHeaders(int64_t sinceNs, const char* prefix)
Ray Essick92d23b42018-01-29 12:10:30 -0800333{
Andy Hung54c73ce2021-03-30 14:25:54 -0700334 std::stringstream result;
Ray Essickf27e9872019-12-07 06:28:46 -0800335 if (mediametrics::Item::isEnabled()) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700336 result << "Metrics gathering: enabled\n";
Ray Essickb5fac8e2016-12-12 11:33:56 -0800337 } else {
Andy Hung54c73ce2021-03-30 14:25:54 -0700338 result << "Metrics gathering: DISABLED via property\n";
Ray Essickb5fac8e2016-12-12 11:33:56 -0800339 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700340 result << StringPrintf(
Andy Hung17dbaf22019-10-11 14:06:31 -0700341 "Since Boot: Submissions: %lld Accepted: %lld\n",
342 (long long)mItemsSubmitted.load(), (long long)mItemsFinalized);
Andy Hung54c73ce2021-03-30 14:25:54 -0700343 result << StringPrintf(
Andy Hung17dbaf22019-10-11 14:06:31 -0700344 "Records Discarded: %lld (by Count: %lld by Expiration: %lld)\n",
345 (long long)mItemsDiscarded, (long long)mItemsDiscardedCount,
346 (long long)mItemsDiscardedExpire);
Andy Hung709b91e2020-04-04 14:23:36 -0700347 if (prefix != nullptr) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700348 result << "Restricting to prefix " << prefix << "\n";
Andy Hung709b91e2020-04-04 14:23:36 -0700349 }
350 if (sinceNs != 0) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700351 result << "Emitting Queue entries more recent than: " << sinceNs << "\n";
Ray Essickb5fac8e2016-12-12 11:33:56 -0800352 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700353 return result.str();
Ray Essick2e9c63b2017-03-29 15:16:44 -0700354}
355
Andy Hung709b91e2020-04-04 14:23:36 -0700356// TODO: should prefix be a set<string>?
Andy Hung54c73ce2021-03-30 14:25:54 -0700357std::string MediaMetricsService::dumpQueue(int64_t sinceNs, const char* prefix)
Ray Essick92d23b42018-01-29 12:10:30 -0800358{
Ray Essick92d23b42018-01-29 12:10:30 -0800359 if (mItems.empty()) {
Andy Hung54c73ce2021-03-30 14:25:54 -0700360 return "empty\n";
Andy Hung709b91e2020-04-04 14:23:36 -0700361 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700362 std::stringstream result;
Andy Hung709b91e2020-04-04 14:23:36 -0700363 int slot = 0;
364 for (const auto &item : mItems) { // TODO: consider std::lower_bound() on mItems
365 if (item->getTimestamp() < sinceNs) { // sinceNs == 0 means all items shown
366 continue;
Ray Essick3938dc62016-11-01 08:56:56 -0700367 }
Andy Hung709b91e2020-04-04 14:23:36 -0700368 if (prefix != nullptr && !startsWith(item->getKey(), prefix)) {
369 ALOGV("%s: omit '%s', it's not '%s'",
370 __func__, item->getKey().c_str(), prefix);
371 continue;
372 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700373 result << StringPrintf("%5d: %s\n", slot, item->toString().c_str());
Andy Hung709b91e2020-04-04 14:23:36 -0700374 slot++;
Ray Essick3938dc62016-11-01 08:56:56 -0700375 }
Andy Hung54c73ce2021-03-30 14:25:54 -0700376 return result.str();
Ray Essick3938dc62016-11-01 08:56:56 -0700377}
378
379//
380// Our Cheap in-core, non-persistent records management.
Ray Essick3938dc62016-11-01 08:56:56 -0700381
Ray Essick72a436b2018-06-14 15:08:13 -0700382// if item != NULL, it's the item we just inserted
383// true == more items eligible to be recovered
Andy Hungf7c14102020-04-18 14:54:08 -0700384bool MediaMetricsService::expirations(const std::shared_ptr<const mediametrics::Item>& item)
Ray Essick92d23b42018-01-29 12:10:30 -0800385{
Ray Essick72a436b2018-06-14 15:08:13 -0700386 bool more = false;
Ray Essicke5db6db2017-11-10 15:54:32 -0800387
Andy Hung17dbaf22019-10-11 14:06:31 -0700388 // check queue size
389 size_t overlimit = 0;
390 if (mMaxRecords > 0 && mItems.size() > mMaxRecords) {
391 overlimit = mItems.size() - mMaxRecords;
392 if (overlimit > mMaxRecordsExpiredAtOnce) {
393 more = true;
394 overlimit = mMaxRecordsExpiredAtOnce;
Ray Essickf65f4212017-08-31 11:41:19 -0700395 }
396 }
397
Andy Hung17dbaf22019-10-11 14:06:31 -0700398 // check queue times
399 size_t expired = 0;
400 if (!more && mMaxRecordAgeNs > 0) {
401 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
402 // we check one at a time, skip search would be more efficient.
403 size_t i = overlimit;
404 for (; i < mItems.size(); ++i) {
405 auto &oitem = mItems[i];
Ray Essickf65f4212017-08-31 11:41:19 -0700406 nsecs_t when = oitem->getTimestamp();
Andy Hung82a074b2019-12-03 14:16:45 -0800407 if (oitem.get() == item.get()) {
Ray Essicke5db6db2017-11-10 15:54:32 -0800408 break;
409 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700410 if (now > when && (now - when) <= mMaxRecordAgeNs) {
Andy Hunged416da2020-03-05 18:42:55 -0800411 break; // Note SYSTEM_TIME_REALTIME may not be monotonic.
Ray Essickf65f4212017-08-31 11:41:19 -0700412 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700413 if (i >= mMaxRecordsExpiredAtOnce) {
Ray Essick72a436b2018-06-14 15:08:13 -0700414 // this represents "one too many"; tell caller there are
415 // more to be reclaimed.
416 more = true;
417 break;
418 }
Ray Essick3938dc62016-11-01 08:56:56 -0700419 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700420 expired = i - overlimit;
Ray Essick3938dc62016-11-01 08:56:56 -0700421 }
Ray Essick72a436b2018-06-14 15:08:13 -0700422
Andy Hung17dbaf22019-10-11 14:06:31 -0700423 if (const size_t toErase = overlimit + expired;
424 toErase > 0) {
Andy Hungc14ee142021-03-10 16:39:02 -0800425 mItemsDiscardedCount += (int64_t)overlimit;
426 mItemsDiscardedExpire += (int64_t)expired;
427 mItemsDiscarded += (int64_t)toErase;
428 mItems.erase(mItems.begin(), mItems.begin() + (ptrdiff_t)toErase); // erase from front
Andy Hung17dbaf22019-10-11 14:06:31 -0700429 }
Ray Essick72a436b2018-06-14 15:08:13 -0700430 return more;
431}
432
Ray Essickf27e9872019-12-07 06:28:46 -0800433void MediaMetricsService::processExpirations()
Ray Essick72a436b2018-06-14 15:08:13 -0700434{
435 bool more;
436 do {
437 sleep(1);
Andy Hung17dbaf22019-10-11 14:06:31 -0700438 std::lock_guard _l(mLock);
Andy Hungf7c14102020-04-18 14:54:08 -0700439 more = expirations(nullptr);
Ray Essick72a436b2018-06-14 15:08:13 -0700440 } while (more);
Ray Essick72a436b2018-06-14 15:08:13 -0700441}
442
Ray Essickf27e9872019-12-07 06:28:46 -0800443void MediaMetricsService::saveItem(const std::shared_ptr<const mediametrics::Item>& item)
Ray Essick72a436b2018-06-14 15:08:13 -0700444{
Andy Hung17dbaf22019-10-11 14:06:31 -0700445 std::lock_guard _l(mLock);
446 // we assume the items are roughly in time order.
447 mItems.emplace_back(item);
Robert Shih2e15aed2021-03-16 18:30:35 -0700448 if (isPullable(item->getKey())) {
449 registerStatsdCallbacksIfNeeded();
450 mPullableItems[item->getKey()].emplace_back(item);
451 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700452 ++mItemsFinalized;
Andy Hungf7c14102020-04-18 14:54:08 -0700453 if (expirations(item)
Andy Hung17dbaf22019-10-11 14:06:31 -0700454 && (!mExpireFuture.valid()
455 || mExpireFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready)) {
456 mExpireFuture = std::async(std::launch::async, [this] { processExpirations(); });
Ray Essick72a436b2018-06-14 15:08:13 -0700457 }
Ray Essick3938dc62016-11-01 08:56:56 -0700458}
459
Andy Hung17dbaf22019-10-11 14:06:31 -0700460/* static */
Ray Essickf27e9872019-12-07 06:28:46 -0800461bool MediaMetricsService::isContentValid(const mediametrics::Item *item, bool isTrusted)
Ray Essickd38e1742017-01-23 15:17:06 -0800462{
Andy Hung17dbaf22019-10-11 14:06:31 -0700463 if (isTrusted) return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800464 // untrusted uids can only send us a limited set of keys
Andy Hung17dbaf22019-10-11 14:06:31 -0700465 const std::string &key = item->getKey();
Andy Hung06f3aba2019-12-03 16:36:42 -0800466 if (startsWith(key, "audio.")) return true;
Edwin Wong8d188352020-02-11 11:59:34 -0800467 if (startsWith(key, "drm.vendor.")) return true;
468 // the list of allowedKey uses statsd_handlers
469 // in iface_statsd.cpp as reference
470 // drmmanager is from a trusted uid, therefore not needed here
Andy Hung17dbaf22019-10-11 14:06:31 -0700471 for (const char *allowedKey : {
Andy Hung06f3aba2019-12-03 16:36:42 -0800472 // legacy audio
Andy Hung17dbaf22019-10-11 14:06:31 -0700473 "audiopolicy",
474 "audiorecord",
475 "audiothread",
476 "audiotrack",
Andy Hung06f3aba2019-12-03 16:36:42 -0800477 // other media
Andy Hung17dbaf22019-10-11 14:06:31 -0700478 "codec",
479 "extractor",
Edwin Wong8d188352020-02-11 11:59:34 -0800480 "mediadrm",
Santiago Seifert49fb4522020-08-07 13:48:45 +0100481 "mediaparser",
Andy Hung17dbaf22019-10-11 14:06:31 -0700482 "nuplayer",
483 }) {
484 if (key == allowedKey) {
485 return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800486 }
487 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700488 ALOGD("%s: invalid key: %s", __func__, item->toString().c_str());
Ray Essick3938dc62016-11-01 08:56:56 -0700489 return false;
490}
491
Andy Hung17dbaf22019-10-11 14:06:31 -0700492// are we rate limited, normally false
Ray Essickf27e9872019-12-07 06:28:46 -0800493bool MediaMetricsService::isRateLimited(mediametrics::Item *) const
Andy Hung17dbaf22019-10-11 14:06:31 -0700494{
495 return false;
496}
497
Robert Shih2e15aed2021-03-16 18:30:35 -0700498void MediaMetricsService::registerStatsdCallbacksIfNeeded()
499{
500 if (mStatsdRegistered.test_and_set()) {
501 return;
502 }
503 auto tag = android::util::MEDIA_DRM_ACTIVITY_INFO;
504 auto cb = MediaMetricsService::pullAtomCallback;
505 AStatsManager_setPullAtomCallback(tag, /* metadata */ nullptr, cb, this);
506}
507
508/* static */
509bool MediaMetricsService::isPullable(const std::string &key)
510{
511 static const std::set<std::string> pullableKeys{
512 "mediadrm",
513 };
514 return pullableKeys.count(key);
515}
516
517/* static */
518std::string MediaMetricsService::atomTagToKey(int32_t atomTag)
519{
520 switch (atomTag) {
521 case android::util::MEDIA_DRM_ACTIVITY_INFO:
522 return "mediadrm";
523 }
524 return {};
525}
526
527/* static */
528AStatsManager_PullAtomCallbackReturn MediaMetricsService::pullAtomCallback(
529 int32_t atomTag, AStatsEventList* data, void* cookie)
530{
531 MediaMetricsService* svc = reinterpret_cast<MediaMetricsService*>(cookie);
532 return svc->pullItems(atomTag, data);
533}
534
535AStatsManager_PullAtomCallbackReturn MediaMetricsService::pullItems(
536 int32_t atomTag, AStatsEventList* data)
537{
538 const std::string key(atomTagToKey(atomTag));
539 if (key.empty()) {
540 return AStatsManager_PULL_SKIP;
541 }
542 std::lock_guard _l(mLock);
543 for (auto &item : mPullableItems[key]) {
544 if (const auto sitem = item.lock()) {
545 dump2Statsd(sitem, data);
546 }
547 }
548 mPullableItems[key].clear();
549 return AStatsManager_PULL_SUCCESS;
550}
Ray Essick3938dc62016-11-01 08:56:56 -0700551} // namespace android