blob: 3b3dc3ea07dabd09d9952f9c4a8103168962e870 [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"
Ray Essick3938dc62016-11-01 08:56:56 -070022
Andy Hung17dbaf22019-10-11 14:06:31 -070023#include <pwd.h> //getpwuid
24
Andy Hung17dbaf22019-10-11 14:06:31 -070025#include <android/content/pm/IPackageManagerNative.h> // package info
Andy Hung55aaf522019-12-03 15:07:51 -080026#include <audio_utils/clock.h> // clock conversions
Andy Hung17dbaf22019-10-11 14:06:31 -070027#include <binder/IPCThreadState.h> // get calling uid
28#include <cutils/properties.h> // for property_get
Andy Hung9099a1a2020-04-04 14:23:36 -070029#include <mediautils/MemoryLeakTrackUtil.h>
30#include <memunreachable/memunreachable.h>
Andy Hung17dbaf22019-10-11 14:06:31 -070031#include <private/android_filesystem_config.h> // UID
32
Ray Essick3938dc62016-11-01 08:56:56 -070033namespace android {
34
Andy Hung1efc9c62019-12-03 13:43:33 -080035using namespace mediametrics;
36
Ray Essickf65f4212017-08-31 11:41:19 -070037// individual records kept in memory: age or count
Ray Essick72a436b2018-06-14 15:08:13 -070038// age: <= 28 hours (1 1/6 days)
Ray Essickf65f4212017-08-31 11:41:19 -070039// count: hard limit of # records
40// (0 for either of these disables that threshold)
Ray Essick72a436b2018-06-14 15:08:13 -070041//
Andy Hung17dbaf22019-10-11 14:06:31 -070042static constexpr nsecs_t kMaxRecordAgeNs = 28 * 3600 * NANOS_PER_SECOND;
Ray Essick23f4d6c2019-06-20 10:16:37 -070043// 2019/6: average daily per device is currently 375-ish;
44// setting this to 2000 is large enough to catch most devices
45// we'll lose some data on very very media-active devices, but only for
46// the gms collection; statsd will have already covered those for us.
47// This also retains enough information to help with bugreports
Andy Hung17dbaf22019-10-11 14:06:31 -070048static constexpr size_t kMaxRecords = 2000;
Ray Essick72a436b2018-06-14 15:08:13 -070049
50// max we expire in a single call, to constrain how long we hold the
51// mutex, which also constrains how long a client might wait.
Andy Hung17dbaf22019-10-11 14:06:31 -070052static constexpr size_t kMaxExpiredAtOnce = 50;
Ray Essick72a436b2018-06-14 15:08:13 -070053
54// TODO: need to look at tuning kMaxRecords and friends for low-memory devices
Ray Essick2e9c63b2017-03-29 15:16:44 -070055
Andy Hung55aaf522019-12-03 15:07:51 -080056/* static */
Ray Essickf27e9872019-12-07 06:28:46 -080057nsecs_t MediaMetricsService::roundTime(nsecs_t timeNs)
Andy Hung55aaf522019-12-03 15:07:51 -080058{
59 return (timeNs + NANOS_PER_SECOND / 2) / NANOS_PER_SECOND * NANOS_PER_SECOND;
60}
61
Andy Hunga85efab2019-12-23 11:41:29 -080062/* static */
63bool MediaMetricsService::useUidForPackage(
64 const std::string& package, const std::string& installer)
65{
66 if (strchr(package.c_str(), '.') == NULL) {
67 return false; // not of form 'com.whatever...'; assume internal and ok
68 } else if (strncmp(package.c_str(), "android.", 8) == 0) {
69 return false; // android.* packages are assumed fine
70 } else if (strncmp(installer.c_str(), "com.android.", 12) == 0) {
71 return false; // from play store
72 } else if (strncmp(installer.c_str(), "com.google.", 11) == 0) {
73 return false; // some google source
74 } else if (strcmp(installer.c_str(), "preload") == 0) {
75 return false; // preloads
76 } else {
77 return true; // we're not sure where it came from, use uid only.
78 }
79}
80
Andy Hungce9b6632020-04-28 20:15:17 -070081/* static */
82std::pair<std::string, int64_t>
83MediaMetricsService::getSanitizedPackageNameAndVersionCode(uid_t uid) {
84 // Meyer's singleton, initialized on first access.
85 // mUidInfo is locked internally.
86 static mediautils::UidInfo uidInfo;
87
88 // get info.
89 mediautils::UidInfo::Info info = uidInfo.getInfo(uid);
90 if (useUidForPackage(info.package, info.installer)) {
91 return { std::to_string(uid), /* versionCode */ 0 };
92 } else {
93 return { info.package, info.versionCode };
94 }
95}
96
97/* static */
98std::string MediaMetricsService::tokenizer(std::string::const_iterator& it,
99 const std::string::const_iterator& end, const char *reserved) {
100 // consume leading white space
101 for (; it != end && std::isspace(*it); ++it);
102 if (it == end) return {};
103
104 auto start = it;
105 // parse until we hit a reserved keyword or space
106 if (strchr(reserved, *it)) return {start, ++it};
107 for (;;) {
108 ++it;
109 if (it == end || std::isspace(*it) || strchr(reserved, *it)) return {start, it};
110 }
111}
112
113/* static */
114std::vector<std::pair<std::string, std::string>>
115MediaMetricsService::getDeviceAddressPairs(const std::string& devices) {
116 std::vector<std::pair<std::string, std::string>> result;
117
118 // Currently, the device format is EXACTLY
119 // (device1, addr1)|(device2, addr2)|...
120
121 static constexpr char delim[] = "()|,";
122 for (auto it = devices.begin(); ; ) {
123 auto token = tokenizer(it, devices.end(), delim);
124 if (token != "(") return result;
125
126 auto device = tokenizer(it, devices.end(), delim);
127 if (device.empty() || !std::isalnum(device[0])) return result;
128
129 token = tokenizer(it, devices.end(), delim);
130 if (token != ",") return result;
131
132 // special handling here for empty addresses
133 auto address = tokenizer(it, devices.end(), delim);
134 if (address.empty() || !std::isalnum(device[0])) return result;
135 if (address == ")") { // no address, just the ")"
136 address.clear();
137 } else {
138 token = tokenizer(it, devices.end(), delim);
139 if (token != ")") return result;
140 }
141
142 result.emplace_back(std::move(device), std::move(address));
143
144 token = tokenizer(it, devices.end(), delim);
145 if (token != "|") return result; // this includes end of string detection
146 }
147}
148
Ray Essickf27e9872019-12-07 06:28:46 -0800149MediaMetricsService::MediaMetricsService()
Ray Essick2e9c63b2017-03-29 15:16:44 -0700150 : mMaxRecords(kMaxRecords),
Ray Essickf65f4212017-08-31 11:41:19 -0700151 mMaxRecordAgeNs(kMaxRecordAgeNs),
Andy Hung3b4c1f02020-01-23 18:58:32 -0800152 mMaxRecordsExpiredAtOnce(kMaxExpiredAtOnce)
Andy Hung17dbaf22019-10-11 14:06:31 -0700153{
154 ALOGD("%s", __func__);
Ray Essick3938dc62016-11-01 08:56:56 -0700155}
156
Ray Essickf27e9872019-12-07 06:28:46 -0800157MediaMetricsService::~MediaMetricsService()
Andy Hung17dbaf22019-10-11 14:06:31 -0700158{
159 ALOGD("%s", __func__);
160 // the class destructor clears anyhow, but we enforce clearing items first.
161 mItemsDiscarded += mItems.size();
162 mItems.clear();
Ray Essick3938dc62016-11-01 08:56:56 -0700163}
164
Ray Essickf27e9872019-12-07 06:28:46 -0800165status_t MediaMetricsService::submitInternal(mediametrics::Item *item, bool release)
Ray Essick92d23b42018-01-29 12:10:30 -0800166{
Andy Hung55aaf522019-12-03 15:07:51 -0800167 // calling PID is 0 for one-way calls.
168 const pid_t pid = IPCThreadState::self()->getCallingPid();
169 const pid_t pid_given = item->getPid();
170 const uid_t uid = IPCThreadState::self()->getCallingUid();
171 const uid_t uid_given = item->getUid();
Ray Essickd38e1742017-01-23 15:17:06 -0800172
Andy Hung55aaf522019-12-03 15:07:51 -0800173 //ALOGD("%s: caller pid=%d uid=%d, item pid=%d uid=%d", __func__,
174 // (int)pid, (int)uid, (int) pid_given, (int)uid_given);
Ray Essickd38e1742017-01-23 15:17:06 -0800175
Andy Hung17dbaf22019-10-11 14:06:31 -0700176 bool isTrusted;
177 switch (uid) {
Andy Hung55aaf522019-12-03 15:07:51 -0800178 case AID_AUDIOSERVER:
179 case AID_BLUETOOTH:
180 case AID_CAMERA:
Andy Hung17dbaf22019-10-11 14:06:31 -0700181 case AID_DRM:
182 case AID_MEDIA:
183 case AID_MEDIA_CODEC:
184 case AID_MEDIA_EX:
185 case AID_MEDIA_DRM:
Andy Hung5d3f2d12020-03-04 19:55:03 -0800186 // case AID_SHELL: // DEBUG ONLY - used for mediametrics_tests to add new keys
Andy Hung55aaf522019-12-03 15:07:51 -0800187 case AID_SYSTEM:
Andy Hung17dbaf22019-10-11 14:06:31 -0700188 // trusted source, only override default values
189 isTrusted = true;
Andy Hung55aaf522019-12-03 15:07:51 -0800190 if (uid_given == (uid_t)-1) {
Ray Essickd38e1742017-01-23 15:17:06 -0800191 item->setUid(uid);
Andy Hung17dbaf22019-10-11 14:06:31 -0700192 }
Andy Hung55aaf522019-12-03 15:07:51 -0800193 if (pid_given == (pid_t)-1) {
194 item->setPid(pid); // if one-way then this is 0.
Andy Hung17dbaf22019-10-11 14:06:31 -0700195 }
196 break;
197 default:
198 isTrusted = false;
Andy Hung55aaf522019-12-03 15:07:51 -0800199 item->setPid(pid); // always use calling pid, if one-way then this is 0.
Andy Hung17dbaf22019-10-11 14:06:31 -0700200 item->setUid(uid);
201 break;
Ray Essickd38e1742017-01-23 15:17:06 -0800202 }
203
Andy Hunga85efab2019-12-23 11:41:29 -0800204 // Overwrite package name and version if the caller was untrusted or empty
205 if (!isTrusted || item->getPkgName().empty()) {
206 const uid_t uid = item->getUid();
Andy Hungce9b6632020-04-28 20:15:17 -0700207 const auto [ pkgName, version ] =
208 MediaMetricsService::getSanitizedPackageNameAndVersionCode(uid);
209 item->setPkgName(pkgName);
210 item->setPkgVersionCode(version);
Adam Stone21c72122017-09-05 19:02:06 -0700211 }
212
Andy Hung5d3f2d12020-03-04 19:55:03 -0800213 ALOGV("%s: isTrusted:%d given uid %d; sanitized uid: %d sanitized pkg: %s "
Andy Hung17dbaf22019-10-11 14:06:31 -0700214 "sanitized pkg version: %lld",
215 __func__,
Andy Hung5d3f2d12020-03-04 19:55:03 -0800216 (int)isTrusted,
Adam Stone21c72122017-09-05 19:02:06 -0700217 uid_given, item->getUid(),
218 item->getPkgName().c_str(),
Andy Hung17dbaf22019-10-11 14:06:31 -0700219 (long long)item->getPkgVersionCode());
Ray Essick3938dc62016-11-01 08:56:56 -0700220
221 mItemsSubmitted++;
222
223 // validate the record; we discard if we don't like it
Andy Hung17dbaf22019-10-11 14:06:31 -0700224 if (isContentValid(item, isTrusted) == false) {
Andy Hunga87e69c2019-10-18 10:07:40 -0700225 if (release) delete item;
226 return PERMISSION_DENIED;
Ray Essick3938dc62016-11-01 08:56:56 -0700227 }
228
Ray Essick92d23b42018-01-29 12:10:30 -0800229 // XXX: if we have a sessionid in the new record, look to make
Ray Essick3938dc62016-11-01 08:56:56 -0700230 // sure it doesn't appear in the finalized list.
Ray Essick3938dc62016-11-01 08:56:56 -0700231
Ray Essick92d23b42018-01-29 12:10:30 -0800232 if (item->count() == 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700233 ALOGV("%s: dropping empty record...", __func__);
Andy Hunga87e69c2019-10-18 10:07:40 -0700234 if (release) delete item;
235 return BAD_VALUE;
Ray Essick3938dc62016-11-01 08:56:56 -0700236 }
Ray Essick92d23b42018-01-29 12:10:30 -0800237
Andy Hung55aaf522019-12-03 15:07:51 -0800238 if (!isTrusted || item->getTimestamp() == 0) {
Andy Hung3b4c1f02020-01-23 18:58:32 -0800239 // Westworld logs two times for events: ElapsedRealTimeNs (BOOTTIME) and
240 // WallClockTimeNs (REALTIME), but currently logs REALTIME to cloud.
Andy Hung55aaf522019-12-03 15:07:51 -0800241 //
Andy Hung3b4c1f02020-01-23 18:58:32 -0800242 // For consistency and correlation with other logging mechanisms
243 // we use REALTIME here.
244 const int64_t now = systemTime(SYSTEM_TIME_REALTIME);
Andy Hung55aaf522019-12-03 15:07:51 -0800245 item->setTimestamp(now);
246 }
247
Andy Hung82a074b2019-12-03 14:16:45 -0800248 // now attach either the item or its dup to a const shared pointer
Ray Essickf27e9872019-12-07 06:28:46 -0800249 std::shared_ptr<const mediametrics::Item> sitem(release ? item : item->dup());
Ray Essick6ce27e52019-02-15 10:58:05 -0800250
Andy Hung06f3aba2019-12-03 16:36:42 -0800251 (void)mAudioAnalytics.submit(sitem, isTrusted);
252
Ray Essickf27e9872019-12-07 06:28:46 -0800253 extern bool dump2Statsd(const std::shared_ptr<const mediametrics::Item>& item);
Andy Hung82a074b2019-12-03 14:16:45 -0800254 (void)dump2Statsd(sitem); // failure should be logged in function.
255 saveItem(sitem);
Andy Hunga87e69c2019-10-18 10:07:40 -0700256 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700257}
258
Ray Essickf27e9872019-12-07 06:28:46 -0800259status_t MediaMetricsService::dump(int fd, const Vector<String16>& args)
Ray Essick3938dc62016-11-01 08:56:56 -0700260{
Ray Essick3938dc62016-11-01 08:56:56 -0700261 String8 result;
262
263 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700264 result.appendFormat("Permission Denial: "
Ray Essickf27e9872019-12-07 06:28:46 -0800265 "can't dump MediaMetricsService from pid=%d, uid=%d\n",
Ray Essick3938dc62016-11-01 08:56:56 -0700266 IPCThreadState::self()->getCallingPid(),
267 IPCThreadState::self()->getCallingUid());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800268 write(fd, result.string(), result.size());
269 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700270 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800271
Andy Hung709b91e2020-04-04 14:23:36 -0700272 static const String16 allOption("--all");
273 static const String16 clearOption("--clear");
Andy Hung9099a1a2020-04-04 14:23:36 -0700274 static const String16 heapOption("--heap");
Andy Hung709b91e2020-04-04 14:23:36 -0700275 static const String16 helpOption("--help");
276 static const String16 prefixOption("--prefix");
277 static const String16 sinceOption("--since");
Andy Hung9099a1a2020-04-04 14:23:36 -0700278 static const String16 unreachableOption("--unreachable");
Andy Hung709b91e2020-04-04 14:23:36 -0700279
280 bool all = false;
281 bool clear = false;
Andy Hung9099a1a2020-04-04 14:23:36 -0700282 bool heap = false;
283 bool unreachable = false;
Andy Hung709b91e2020-04-04 14:23:36 -0700284 int64_t sinceNs = 0;
285 std::string prefix;
Andy Hung9099a1a2020-04-04 14:23:36 -0700286
Andy Hung709b91e2020-04-04 14:23:36 -0700287 const size_t n = args.size();
288 for (size_t i = 0; i < n; i++) {
289 if (args[i] == allOption) {
290 all = true;
291 } else if (args[i] == clearOption) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800292 clear = true;
Andy Hung9099a1a2020-04-04 14:23:36 -0700293 } else if (args[i] == heapOption) {
294 heap = true;
Ray Essick35ad27f2017-01-30 14:04:11 -0800295 } else if (args[i] == helpOption) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700296 // TODO: consider function area dumping.
297 // dumpsys media.metrics audiotrack,codec
298 // or dumpsys media.metrics audiotrack codec
299
Ray Essick35ad27f2017-01-30 14:04:11 -0800300 result.append("Recognized parameters:\n");
Andy Hung709b91e2020-04-04 14:23:36 -0700301 result.append("--all show all records\n");
302 result.append("--clear clear out saved records\n");
303 result.append("--heap show heap usage (top 100)\n");
304 result.append("--help display help\n");
305 result.append("--prefix X process records for component X\n");
306 result.append("--since X X < 0: records from -X seconds in the past\n");
307 result.append(" X = 0: ignore\n");
308 result.append(" X > 0: records from X seconds since Unix epoch\n");
309 result.append("--unreachable show unreachable memory (leaks)\n");
Ray Essick35ad27f2017-01-30 14:04:11 -0800310 write(fd, result.string(), result.size());
311 return NO_ERROR;
Andy Hung709b91e2020-04-04 14:23:36 -0700312 } else if (args[i] == prefixOption) {
313 ++i;
314 if (i < n) {
315 prefix = String8(args[i]).string();
316 }
317 } else if (args[i] == sinceOption) {
318 ++i;
319 if (i < n) {
320 String8 value(args[i]);
321 char *endp;
322 const char *p = value.string();
323 long long sec = strtoll(p, &endp, 10);
324 if (endp == p || *endp != '\0' || sec == 0) {
325 sinceNs = 0;
326 } else if (sec < 0) {
327 sinceNs = systemTime(SYSTEM_TIME_REALTIME) + sec * NANOS_PER_SECOND;
328 } else {
329 sinceNs = sec * NANOS_PER_SECOND;
330 }
331 }
Andy Hung9099a1a2020-04-04 14:23:36 -0700332 } else if (args[i] == unreachableOption) {
333 unreachable = true;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800334 }
335 }
336
Andy Hung17dbaf22019-10-11 14:06:31 -0700337 {
338 std::lock_guard _l(mLock);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800339
Andy Hung17dbaf22019-10-11 14:06:31 -0700340 if (clear) {
341 mItemsDiscarded += mItems.size();
342 mItems.clear();
Andy Hung709b91e2020-04-04 14:23:36 -0700343 mAudioAnalytics.clear();
344 } else {
345 result.appendFormat("Dump of the %s process:\n", kServiceName);
346 const char *prefixptr = prefix.size() > 0 ? prefix.c_str() : nullptr;
Andy Hungf7c14102020-04-18 14:54:08 -0700347 dumpHeaders(result, sinceNs, prefixptr);
348 dumpQueue(result, sinceNs, prefixptr);
Andy Hung709b91e2020-04-04 14:23:36 -0700349
350 // TODO: maybe consider a better way of dumping audio analytics info.
351 const int32_t linesToDump = all ? INT32_MAX : 1000;
352 auto [ dumpString, lines ] = mAudioAnalytics.dump(linesToDump, sinceNs, prefixptr);
353 result.append(dumpString.c_str());
354 if (lines == linesToDump) {
355 result.append("-- some lines may be truncated --\n");
356 }
Andy Hung0f7ad8c2020-01-03 13:24:34 -0800357 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700358 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700359 write(fd, result.string(), result.size());
Andy Hung9099a1a2020-04-04 14:23:36 -0700360
361 // Check heap and unreachable memory outside of lock.
362 if (heap) {
363 dprintf(fd, "\nDumping heap:\n");
364 std::string s = dumpMemoryAddresses(100 /* limit */);
365 write(fd, s.c_str(), s.size());
366 }
367 if (unreachable) {
368 dprintf(fd, "\nDumping unreachable memory:\n");
369 // TODO - should limit be an argument parameter?
370 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
371 write(fd, s.c_str(), s.size());
372 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700373 return NO_ERROR;
374}
375
376// dump headers
Andy Hungf7c14102020-04-18 14:54:08 -0700377void MediaMetricsService::dumpHeaders(String8 &result, int64_t sinceNs, const char* prefix)
Ray Essick92d23b42018-01-29 12:10:30 -0800378{
Ray Essickf27e9872019-12-07 06:28:46 -0800379 if (mediametrics::Item::isEnabled()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700380 result.append("Metrics gathering: enabled\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800381 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700382 result.append("Metrics gathering: DISABLED via property\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800383 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700384 result.appendFormat(
385 "Since Boot: Submissions: %lld Accepted: %lld\n",
386 (long long)mItemsSubmitted.load(), (long long)mItemsFinalized);
387 result.appendFormat(
388 "Records Discarded: %lld (by Count: %lld by Expiration: %lld)\n",
389 (long long)mItemsDiscarded, (long long)mItemsDiscardedCount,
390 (long long)mItemsDiscardedExpire);
Andy Hung709b91e2020-04-04 14:23:36 -0700391 if (prefix != nullptr) {
392 result.appendFormat("Restricting to prefix %s", prefix);
393 }
394 if (sinceNs != 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700395 result.appendFormat(
396 "Emitting Queue entries more recent than: %lld\n",
Andy Hung709b91e2020-04-04 14:23:36 -0700397 (long long)sinceNs);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800398 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700399}
400
Andy Hung709b91e2020-04-04 14:23:36 -0700401// TODO: should prefix be a set<string>?
Andy Hungf7c14102020-04-18 14:54:08 -0700402void MediaMetricsService::dumpQueue(String8 &result, int64_t sinceNs, const char* prefix)
Ray Essick92d23b42018-01-29 12:10:30 -0800403{
Ray Essick92d23b42018-01-29 12:10:30 -0800404 if (mItems.empty()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700405 result.append("empty\n");
Andy Hung709b91e2020-04-04 14:23:36 -0700406 return;
407 }
408
409 int slot = 0;
410 for (const auto &item : mItems) { // TODO: consider std::lower_bound() on mItems
411 if (item->getTimestamp() < sinceNs) { // sinceNs == 0 means all items shown
412 continue;
Ray Essick3938dc62016-11-01 08:56:56 -0700413 }
Andy Hung709b91e2020-04-04 14:23:36 -0700414 if (prefix != nullptr && !startsWith(item->getKey(), prefix)) {
415 ALOGV("%s: omit '%s', it's not '%s'",
416 __func__, item->getKey().c_str(), prefix);
417 continue;
418 }
419 result.appendFormat("%5d: %s\n", slot, item->toString().c_str());
420 slot++;
Ray Essick3938dc62016-11-01 08:56:56 -0700421 }
Ray Essick3938dc62016-11-01 08:56:56 -0700422}
423
424//
425// Our Cheap in-core, non-persistent records management.
Ray Essick3938dc62016-11-01 08:56:56 -0700426
Ray Essick72a436b2018-06-14 15:08:13 -0700427// if item != NULL, it's the item we just inserted
428// true == more items eligible to be recovered
Andy Hungf7c14102020-04-18 14:54:08 -0700429bool MediaMetricsService::expirations(const std::shared_ptr<const mediametrics::Item>& item)
Ray Essick92d23b42018-01-29 12:10:30 -0800430{
Ray Essick72a436b2018-06-14 15:08:13 -0700431 bool more = false;
Ray Essicke5db6db2017-11-10 15:54:32 -0800432
Andy Hung17dbaf22019-10-11 14:06:31 -0700433 // check queue size
434 size_t overlimit = 0;
435 if (mMaxRecords > 0 && mItems.size() > mMaxRecords) {
436 overlimit = mItems.size() - mMaxRecords;
437 if (overlimit > mMaxRecordsExpiredAtOnce) {
438 more = true;
439 overlimit = mMaxRecordsExpiredAtOnce;
Ray Essickf65f4212017-08-31 11:41:19 -0700440 }
441 }
442
Andy Hung17dbaf22019-10-11 14:06:31 -0700443 // check queue times
444 size_t expired = 0;
445 if (!more && mMaxRecordAgeNs > 0) {
446 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
447 // we check one at a time, skip search would be more efficient.
448 size_t i = overlimit;
449 for (; i < mItems.size(); ++i) {
450 auto &oitem = mItems[i];
Ray Essickf65f4212017-08-31 11:41:19 -0700451 nsecs_t when = oitem->getTimestamp();
Andy Hung82a074b2019-12-03 14:16:45 -0800452 if (oitem.get() == item.get()) {
Ray Essicke5db6db2017-11-10 15:54:32 -0800453 break;
454 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700455 if (now > when && (now - when) <= mMaxRecordAgeNs) {
Andy Hunged416da2020-03-05 18:42:55 -0800456 break; // Note SYSTEM_TIME_REALTIME may not be monotonic.
Ray Essickf65f4212017-08-31 11:41:19 -0700457 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700458 if (i >= mMaxRecordsExpiredAtOnce) {
Ray Essick72a436b2018-06-14 15:08:13 -0700459 // this represents "one too many"; tell caller there are
460 // more to be reclaimed.
461 more = true;
462 break;
463 }
Ray Essick3938dc62016-11-01 08:56:56 -0700464 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700465 expired = i - overlimit;
Ray Essick3938dc62016-11-01 08:56:56 -0700466 }
Ray Essick72a436b2018-06-14 15:08:13 -0700467
Andy Hung17dbaf22019-10-11 14:06:31 -0700468 if (const size_t toErase = overlimit + expired;
469 toErase > 0) {
470 mItemsDiscardedCount += overlimit;
471 mItemsDiscardedExpire += expired;
472 mItemsDiscarded += toErase;
473 mItems.erase(mItems.begin(), mItems.begin() + toErase); // erase from front
474 }
Ray Essick72a436b2018-06-14 15:08:13 -0700475 return more;
476}
477
Ray Essickf27e9872019-12-07 06:28:46 -0800478void MediaMetricsService::processExpirations()
Ray Essick72a436b2018-06-14 15:08:13 -0700479{
480 bool more;
481 do {
482 sleep(1);
Andy Hung17dbaf22019-10-11 14:06:31 -0700483 std::lock_guard _l(mLock);
Andy Hungf7c14102020-04-18 14:54:08 -0700484 more = expirations(nullptr);
Ray Essick72a436b2018-06-14 15:08:13 -0700485 } while (more);
Ray Essick72a436b2018-06-14 15:08:13 -0700486}
487
Ray Essickf27e9872019-12-07 06:28:46 -0800488void MediaMetricsService::saveItem(const std::shared_ptr<const mediametrics::Item>& item)
Ray Essick72a436b2018-06-14 15:08:13 -0700489{
Andy Hung17dbaf22019-10-11 14:06:31 -0700490 std::lock_guard _l(mLock);
491 // we assume the items are roughly in time order.
492 mItems.emplace_back(item);
493 ++mItemsFinalized;
Andy Hungf7c14102020-04-18 14:54:08 -0700494 if (expirations(item)
Andy Hung17dbaf22019-10-11 14:06:31 -0700495 && (!mExpireFuture.valid()
496 || mExpireFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready)) {
497 mExpireFuture = std::async(std::launch::async, [this] { processExpirations(); });
Ray Essick72a436b2018-06-14 15:08:13 -0700498 }
Ray Essick3938dc62016-11-01 08:56:56 -0700499}
500
Andy Hung17dbaf22019-10-11 14:06:31 -0700501/* static */
Ray Essickf27e9872019-12-07 06:28:46 -0800502bool MediaMetricsService::isContentValid(const mediametrics::Item *item, bool isTrusted)
Ray Essickd38e1742017-01-23 15:17:06 -0800503{
Andy Hung17dbaf22019-10-11 14:06:31 -0700504 if (isTrusted) return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800505 // untrusted uids can only send us a limited set of keys
Andy Hung17dbaf22019-10-11 14:06:31 -0700506 const std::string &key = item->getKey();
Andy Hung06f3aba2019-12-03 16:36:42 -0800507 if (startsWith(key, "audio.")) return true;
Edwin Wong8d188352020-02-11 11:59:34 -0800508 if (startsWith(key, "drm.vendor.")) return true;
509 // the list of allowedKey uses statsd_handlers
510 // in iface_statsd.cpp as reference
511 // drmmanager is from a trusted uid, therefore not needed here
Andy Hung17dbaf22019-10-11 14:06:31 -0700512 for (const char *allowedKey : {
Andy Hung06f3aba2019-12-03 16:36:42 -0800513 // legacy audio
Andy Hung17dbaf22019-10-11 14:06:31 -0700514 "audiopolicy",
515 "audiorecord",
516 "audiothread",
517 "audiotrack",
Andy Hung06f3aba2019-12-03 16:36:42 -0800518 // other media
Andy Hung17dbaf22019-10-11 14:06:31 -0700519 "codec",
520 "extractor",
Edwin Wong8d188352020-02-11 11:59:34 -0800521 "mediadrm",
Andy Hung17dbaf22019-10-11 14:06:31 -0700522 "nuplayer",
523 }) {
524 if (key == allowedKey) {
525 return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800526 }
527 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700528 ALOGD("%s: invalid key: %s", __func__, item->toString().c_str());
Ray Essick3938dc62016-11-01 08:56:56 -0700529 return false;
530}
531
Andy Hung17dbaf22019-10-11 14:06:31 -0700532// are we rate limited, normally false
Ray Essickf27e9872019-12-07 06:28:46 -0800533bool MediaMetricsService::isRateLimited(mediametrics::Item *) const
Andy Hung17dbaf22019-10-11 14:06:31 -0700534{
535 return false;
536}
537
Ray Essick3938dc62016-11-01 08:56:56 -0700538} // namespace android