blob: bf6e4289faa753334af40c091d22b9e27e92c71f [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 Hung3ab1b322020-05-18 10:47:31 -070035using mediametrics::Item;
36using mediametrics::startsWith;
Andy Hung1efc9c62019-12-03 13:43:33 -080037
Ray Essickf65f4212017-08-31 11:41:19 -070038// individual records kept in memory: age or count
Ray Essick72a436b2018-06-14 15:08:13 -070039// age: <= 28 hours (1 1/6 days)
Ray Essickf65f4212017-08-31 11:41:19 -070040// count: hard limit of # records
41// (0 for either of these disables that threshold)
Ray Essick72a436b2018-06-14 15:08:13 -070042//
Andy Hung17dbaf22019-10-11 14:06:31 -070043static constexpr nsecs_t kMaxRecordAgeNs = 28 * 3600 * NANOS_PER_SECOND;
Ray Essick23f4d6c2019-06-20 10:16:37 -070044// 2019/6: average daily per device is currently 375-ish;
45// setting this to 2000 is large enough to catch most devices
46// we'll lose some data on very very media-active devices, but only for
47// the gms collection; statsd will have already covered those for us.
48// This also retains enough information to help with bugreports
Andy Hung17dbaf22019-10-11 14:06:31 -070049static constexpr size_t kMaxRecords = 2000;
Ray Essick72a436b2018-06-14 15:08:13 -070050
51// max we expire in a single call, to constrain how long we hold the
52// mutex, which also constrains how long a client might wait.
Andy Hung17dbaf22019-10-11 14:06:31 -070053static constexpr size_t kMaxExpiredAtOnce = 50;
Ray Essick72a436b2018-06-14 15:08:13 -070054
55// TODO: need to look at tuning kMaxRecords and friends for low-memory devices
Ray Essick2e9c63b2017-03-29 15:16:44 -070056
Andy Hung55aaf522019-12-03 15:07:51 -080057/* static */
Ray Essickf27e9872019-12-07 06:28:46 -080058nsecs_t MediaMetricsService::roundTime(nsecs_t timeNs)
Andy Hung55aaf522019-12-03 15:07:51 -080059{
60 return (timeNs + NANOS_PER_SECOND / 2) / NANOS_PER_SECOND * NANOS_PER_SECOND;
61}
62
Andy Hunga85efab2019-12-23 11:41:29 -080063/* static */
64bool MediaMetricsService::useUidForPackage(
65 const std::string& package, const std::string& installer)
66{
Andy Hung3ab1b322020-05-18 10:47:31 -070067 if (strchr(package.c_str(), '.') == nullptr) {
Andy Hunga85efab2019-12-23 11:41:29 -080068 return false; // not of form 'com.whatever...'; assume internal and ok
69 } else if (strncmp(package.c_str(), "android.", 8) == 0) {
70 return false; // android.* packages are assumed fine
71 } else if (strncmp(installer.c_str(), "com.android.", 12) == 0) {
72 return false; // from play store
73 } else if (strncmp(installer.c_str(), "com.google.", 11) == 0) {
74 return false; // some google source
75 } else if (strcmp(installer.c_str(), "preload") == 0) {
76 return false; // preloads
77 } else {
78 return true; // we're not sure where it came from, use uid only.
79 }
80}
81
Andy Hungce9b6632020-04-28 20:15:17 -070082/* static */
83std::pair<std::string, int64_t>
84MediaMetricsService::getSanitizedPackageNameAndVersionCode(uid_t uid) {
85 // Meyer's singleton, initialized on first access.
86 // mUidInfo is locked internally.
87 static mediautils::UidInfo uidInfo;
88
89 // get info.
90 mediautils::UidInfo::Info info = uidInfo.getInfo(uid);
91 if (useUidForPackage(info.package, info.installer)) {
92 return { std::to_string(uid), /* versionCode */ 0 };
93 } else {
94 return { info.package, info.versionCode };
95 }
96}
97
Ray Essickf27e9872019-12-07 06:28:46 -080098MediaMetricsService::MediaMetricsService()
Ray Essick2e9c63b2017-03-29 15:16:44 -070099 : mMaxRecords(kMaxRecords),
Ray Essickf65f4212017-08-31 11:41:19 -0700100 mMaxRecordAgeNs(kMaxRecordAgeNs),
Andy Hung3b4c1f02020-01-23 18:58:32 -0800101 mMaxRecordsExpiredAtOnce(kMaxExpiredAtOnce)
Andy Hung17dbaf22019-10-11 14:06:31 -0700102{
103 ALOGD("%s", __func__);
Ray Essick3938dc62016-11-01 08:56:56 -0700104}
105
Ray Essickf27e9872019-12-07 06:28:46 -0800106MediaMetricsService::~MediaMetricsService()
Andy Hung17dbaf22019-10-11 14:06:31 -0700107{
108 ALOGD("%s", __func__);
109 // the class destructor clears anyhow, but we enforce clearing items first.
110 mItemsDiscarded += mItems.size();
111 mItems.clear();
Ray Essick3938dc62016-11-01 08:56:56 -0700112}
113
Ray Essickf27e9872019-12-07 06:28:46 -0800114status_t MediaMetricsService::submitInternal(mediametrics::Item *item, bool release)
Ray Essick92d23b42018-01-29 12:10:30 -0800115{
Andy Hung55aaf522019-12-03 15:07:51 -0800116 // calling PID is 0 for one-way calls.
117 const pid_t pid = IPCThreadState::self()->getCallingPid();
118 const pid_t pid_given = item->getPid();
119 const uid_t uid = IPCThreadState::self()->getCallingUid();
120 const uid_t uid_given = item->getUid();
Ray Essickd38e1742017-01-23 15:17:06 -0800121
Andy Hung55aaf522019-12-03 15:07:51 -0800122 //ALOGD("%s: caller pid=%d uid=%d, item pid=%d uid=%d", __func__,
123 // (int)pid, (int)uid, (int) pid_given, (int)uid_given);
Ray Essickd38e1742017-01-23 15:17:06 -0800124
Andy Hung17dbaf22019-10-11 14:06:31 -0700125 bool isTrusted;
126 switch (uid) {
Andy Hung55aaf522019-12-03 15:07:51 -0800127 case AID_AUDIOSERVER:
128 case AID_BLUETOOTH:
129 case AID_CAMERA:
Andy Hung17dbaf22019-10-11 14:06:31 -0700130 case AID_DRM:
131 case AID_MEDIA:
132 case AID_MEDIA_CODEC:
133 case AID_MEDIA_EX:
134 case AID_MEDIA_DRM:
Andy Hung5d3f2d12020-03-04 19:55:03 -0800135 // case AID_SHELL: // DEBUG ONLY - used for mediametrics_tests to add new keys
Andy Hung55aaf522019-12-03 15:07:51 -0800136 case AID_SYSTEM:
Andy Hung17dbaf22019-10-11 14:06:31 -0700137 // trusted source, only override default values
138 isTrusted = true;
Andy Hung55aaf522019-12-03 15:07:51 -0800139 if (uid_given == (uid_t)-1) {
Ray Essickd38e1742017-01-23 15:17:06 -0800140 item->setUid(uid);
Andy Hung17dbaf22019-10-11 14:06:31 -0700141 }
Andy Hung55aaf522019-12-03 15:07:51 -0800142 if (pid_given == (pid_t)-1) {
143 item->setPid(pid); // if one-way then this is 0.
Andy Hung17dbaf22019-10-11 14:06:31 -0700144 }
145 break;
146 default:
147 isTrusted = false;
Andy Hung55aaf522019-12-03 15:07:51 -0800148 item->setPid(pid); // always use calling pid, if one-way then this is 0.
Andy Hung17dbaf22019-10-11 14:06:31 -0700149 item->setUid(uid);
150 break;
Ray Essickd38e1742017-01-23 15:17:06 -0800151 }
152
Andy Hunga85efab2019-12-23 11:41:29 -0800153 // Overwrite package name and version if the caller was untrusted or empty
154 if (!isTrusted || item->getPkgName().empty()) {
Andy Hung3ab1b322020-05-18 10:47:31 -0700155 const uid_t uidItem = item->getUid();
Andy Hungce9b6632020-04-28 20:15:17 -0700156 const auto [ pkgName, version ] =
Andy Hung3ab1b322020-05-18 10:47:31 -0700157 MediaMetricsService::getSanitizedPackageNameAndVersionCode(uidItem);
Andy Hungce9b6632020-04-28 20:15:17 -0700158 item->setPkgName(pkgName);
159 item->setPkgVersionCode(version);
Adam Stone21c72122017-09-05 19:02:06 -0700160 }
161
Andy Hung5d3f2d12020-03-04 19:55:03 -0800162 ALOGV("%s: isTrusted:%d given uid %d; sanitized uid: %d sanitized pkg: %s "
Andy Hung17dbaf22019-10-11 14:06:31 -0700163 "sanitized pkg version: %lld",
164 __func__,
Andy Hung5d3f2d12020-03-04 19:55:03 -0800165 (int)isTrusted,
Adam Stone21c72122017-09-05 19:02:06 -0700166 uid_given, item->getUid(),
167 item->getPkgName().c_str(),
Andy Hung17dbaf22019-10-11 14:06:31 -0700168 (long long)item->getPkgVersionCode());
Ray Essick3938dc62016-11-01 08:56:56 -0700169
170 mItemsSubmitted++;
171
172 // validate the record; we discard if we don't like it
Andy Hung17dbaf22019-10-11 14:06:31 -0700173 if (isContentValid(item, isTrusted) == false) {
Andy Hunga87e69c2019-10-18 10:07:40 -0700174 if (release) delete item;
175 return PERMISSION_DENIED;
Ray Essick3938dc62016-11-01 08:56:56 -0700176 }
177
Ray Essick92d23b42018-01-29 12:10:30 -0800178 // XXX: if we have a sessionid in the new record, look to make
Ray Essick3938dc62016-11-01 08:56:56 -0700179 // sure it doesn't appear in the finalized list.
Ray Essick3938dc62016-11-01 08:56:56 -0700180
Ray Essick92d23b42018-01-29 12:10:30 -0800181 if (item->count() == 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700182 ALOGV("%s: dropping empty record...", __func__);
Andy Hunga87e69c2019-10-18 10:07:40 -0700183 if (release) delete item;
184 return BAD_VALUE;
Ray Essick3938dc62016-11-01 08:56:56 -0700185 }
Ray Essick92d23b42018-01-29 12:10:30 -0800186
Andy Hung55aaf522019-12-03 15:07:51 -0800187 if (!isTrusted || item->getTimestamp() == 0) {
Muhammad Qureshi087b37c2020-06-16 16:37:36 -0700188 // Statsd logs two times for events: ElapsedRealTimeNs (BOOTTIME) and
Andy Hung3b4c1f02020-01-23 18:58:32 -0800189 // WallClockTimeNs (REALTIME), but currently logs REALTIME to cloud.
Andy Hung55aaf522019-12-03 15:07:51 -0800190 //
Andy Hung3b4c1f02020-01-23 18:58:32 -0800191 // For consistency and correlation with other logging mechanisms
192 // we use REALTIME here.
193 const int64_t now = systemTime(SYSTEM_TIME_REALTIME);
Andy Hung55aaf522019-12-03 15:07:51 -0800194 item->setTimestamp(now);
195 }
196
Andy Hung82a074b2019-12-03 14:16:45 -0800197 // now attach either the item or its dup to a const shared pointer
Ray Essickf27e9872019-12-07 06:28:46 -0800198 std::shared_ptr<const mediametrics::Item> sitem(release ? item : item->dup());
Ray Essick6ce27e52019-02-15 10:58:05 -0800199
Andy Hung06f3aba2019-12-03 16:36:42 -0800200 (void)mAudioAnalytics.submit(sitem, isTrusted);
201
Ray Essickf27e9872019-12-07 06:28:46 -0800202 extern bool dump2Statsd(const std::shared_ptr<const mediametrics::Item>& item);
Andy Hung82a074b2019-12-03 14:16:45 -0800203 (void)dump2Statsd(sitem); // failure should be logged in function.
204 saveItem(sitem);
Andy Hunga87e69c2019-10-18 10:07:40 -0700205 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700206}
207
Ray Essickf27e9872019-12-07 06:28:46 -0800208status_t MediaMetricsService::dump(int fd, const Vector<String16>& args)
Ray Essick3938dc62016-11-01 08:56:56 -0700209{
Ray Essick3938dc62016-11-01 08:56:56 -0700210 String8 result;
211
212 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700213 result.appendFormat("Permission Denial: "
Ray Essickf27e9872019-12-07 06:28:46 -0800214 "can't dump MediaMetricsService from pid=%d, uid=%d\n",
Ray Essick3938dc62016-11-01 08:56:56 -0700215 IPCThreadState::self()->getCallingPid(),
216 IPCThreadState::self()->getCallingUid());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800217 write(fd, result.string(), result.size());
218 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700219 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800220
Andy Hung709b91e2020-04-04 14:23:36 -0700221 static const String16 allOption("--all");
222 static const String16 clearOption("--clear");
Andy Hung9099a1a2020-04-04 14:23:36 -0700223 static const String16 heapOption("--heap");
Andy Hung709b91e2020-04-04 14:23:36 -0700224 static const String16 helpOption("--help");
225 static const String16 prefixOption("--prefix");
226 static const String16 sinceOption("--since");
Andy Hung9099a1a2020-04-04 14:23:36 -0700227 static const String16 unreachableOption("--unreachable");
Andy Hung709b91e2020-04-04 14:23:36 -0700228
229 bool all = false;
230 bool clear = false;
Andy Hung9099a1a2020-04-04 14:23:36 -0700231 bool heap = false;
232 bool unreachable = false;
Andy Hung709b91e2020-04-04 14:23:36 -0700233 int64_t sinceNs = 0;
234 std::string prefix;
Andy Hung9099a1a2020-04-04 14:23:36 -0700235
Andy Hung709b91e2020-04-04 14:23:36 -0700236 const size_t n = args.size();
237 for (size_t i = 0; i < n; i++) {
238 if (args[i] == allOption) {
239 all = true;
240 } else if (args[i] == clearOption) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800241 clear = true;
Andy Hung9099a1a2020-04-04 14:23:36 -0700242 } else if (args[i] == heapOption) {
243 heap = true;
Ray Essick35ad27f2017-01-30 14:04:11 -0800244 } else if (args[i] == helpOption) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700245 // TODO: consider function area dumping.
246 // dumpsys media.metrics audiotrack,codec
247 // or dumpsys media.metrics audiotrack codec
248
Ray Essick35ad27f2017-01-30 14:04:11 -0800249 result.append("Recognized parameters:\n");
Andy Hung709b91e2020-04-04 14:23:36 -0700250 result.append("--all show all records\n");
251 result.append("--clear clear out saved records\n");
252 result.append("--heap show heap usage (top 100)\n");
253 result.append("--help display help\n");
254 result.append("--prefix X process records for component X\n");
255 result.append("--since X X < 0: records from -X seconds in the past\n");
256 result.append(" X = 0: ignore\n");
257 result.append(" X > 0: records from X seconds since Unix epoch\n");
258 result.append("--unreachable show unreachable memory (leaks)\n");
Ray Essick35ad27f2017-01-30 14:04:11 -0800259 write(fd, result.string(), result.size());
260 return NO_ERROR;
Andy Hung709b91e2020-04-04 14:23:36 -0700261 } else if (args[i] == prefixOption) {
262 ++i;
263 if (i < n) {
264 prefix = String8(args[i]).string();
265 }
266 } else if (args[i] == sinceOption) {
267 ++i;
268 if (i < n) {
269 String8 value(args[i]);
270 char *endp;
271 const char *p = value.string();
Andy Hung3ab1b322020-05-18 10:47:31 -0700272 const auto sec = (int64_t)strtoll(p, &endp, 10);
Andy Hung709b91e2020-04-04 14:23:36 -0700273 if (endp == p || *endp != '\0' || sec == 0) {
274 sinceNs = 0;
275 } else if (sec < 0) {
276 sinceNs = systemTime(SYSTEM_TIME_REALTIME) + sec * NANOS_PER_SECOND;
277 } else {
278 sinceNs = sec * NANOS_PER_SECOND;
279 }
280 }
Andy Hung9099a1a2020-04-04 14:23:36 -0700281 } else if (args[i] == unreachableOption) {
282 unreachable = true;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800283 }
284 }
285
Andy Hung17dbaf22019-10-11 14:06:31 -0700286 {
287 std::lock_guard _l(mLock);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800288
Andy Hung17dbaf22019-10-11 14:06:31 -0700289 if (clear) {
290 mItemsDiscarded += mItems.size();
291 mItems.clear();
Andy Hung709b91e2020-04-04 14:23:36 -0700292 mAudioAnalytics.clear();
293 } else {
294 result.appendFormat("Dump of the %s process:\n", kServiceName);
295 const char *prefixptr = prefix.size() > 0 ? prefix.c_str() : nullptr;
Andy Hungf7c14102020-04-18 14:54:08 -0700296 dumpHeaders(result, sinceNs, prefixptr);
297 dumpQueue(result, sinceNs, prefixptr);
Andy Hung709b91e2020-04-04 14:23:36 -0700298
299 // TODO: maybe consider a better way of dumping audio analytics info.
300 const int32_t linesToDump = all ? INT32_MAX : 1000;
301 auto [ dumpString, lines ] = mAudioAnalytics.dump(linesToDump, sinceNs, prefixptr);
302 result.append(dumpString.c_str());
303 if (lines == linesToDump) {
304 result.append("-- some lines may be truncated --\n");
305 }
Andy Hung0f7ad8c2020-01-03 13:24:34 -0800306 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700307 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700308 write(fd, result.string(), result.size());
Andy Hung9099a1a2020-04-04 14:23:36 -0700309
310 // Check heap and unreachable memory outside of lock.
311 if (heap) {
312 dprintf(fd, "\nDumping heap:\n");
313 std::string s = dumpMemoryAddresses(100 /* limit */);
314 write(fd, s.c_str(), s.size());
315 }
316 if (unreachable) {
317 dprintf(fd, "\nDumping unreachable memory:\n");
318 // TODO - should limit be an argument parameter?
319 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
320 write(fd, s.c_str(), s.size());
321 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700322 return NO_ERROR;
323}
324
325// dump headers
Andy Hungf7c14102020-04-18 14:54:08 -0700326void MediaMetricsService::dumpHeaders(String8 &result, int64_t sinceNs, const char* prefix)
Ray Essick92d23b42018-01-29 12:10:30 -0800327{
Ray Essickf27e9872019-12-07 06:28:46 -0800328 if (mediametrics::Item::isEnabled()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700329 result.append("Metrics gathering: enabled\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800330 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700331 result.append("Metrics gathering: DISABLED via property\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800332 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700333 result.appendFormat(
334 "Since Boot: Submissions: %lld Accepted: %lld\n",
335 (long long)mItemsSubmitted.load(), (long long)mItemsFinalized);
336 result.appendFormat(
337 "Records Discarded: %lld (by Count: %lld by Expiration: %lld)\n",
338 (long long)mItemsDiscarded, (long long)mItemsDiscardedCount,
339 (long long)mItemsDiscardedExpire);
Andy Hung709b91e2020-04-04 14:23:36 -0700340 if (prefix != nullptr) {
341 result.appendFormat("Restricting to prefix %s", prefix);
342 }
343 if (sinceNs != 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700344 result.appendFormat(
345 "Emitting Queue entries more recent than: %lld\n",
Andy Hung709b91e2020-04-04 14:23:36 -0700346 (long long)sinceNs);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800347 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700348}
349
Andy Hung709b91e2020-04-04 14:23:36 -0700350// TODO: should prefix be a set<string>?
Andy Hungf7c14102020-04-18 14:54:08 -0700351void MediaMetricsService::dumpQueue(String8 &result, int64_t sinceNs, const char* prefix)
Ray Essick92d23b42018-01-29 12:10:30 -0800352{
Ray Essick92d23b42018-01-29 12:10:30 -0800353 if (mItems.empty()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700354 result.append("empty\n");
Andy Hung709b91e2020-04-04 14:23:36 -0700355 return;
356 }
357
358 int slot = 0;
359 for (const auto &item : mItems) { // TODO: consider std::lower_bound() on mItems
360 if (item->getTimestamp() < sinceNs) { // sinceNs == 0 means all items shown
361 continue;
Ray Essick3938dc62016-11-01 08:56:56 -0700362 }
Andy Hung709b91e2020-04-04 14:23:36 -0700363 if (prefix != nullptr && !startsWith(item->getKey(), prefix)) {
364 ALOGV("%s: omit '%s', it's not '%s'",
365 __func__, item->getKey().c_str(), prefix);
366 continue;
367 }
368 result.appendFormat("%5d: %s\n", slot, item->toString().c_str());
369 slot++;
Ray Essick3938dc62016-11-01 08:56:56 -0700370 }
Ray Essick3938dc62016-11-01 08:56:56 -0700371}
372
373//
374// Our Cheap in-core, non-persistent records management.
Ray Essick3938dc62016-11-01 08:56:56 -0700375
Ray Essick72a436b2018-06-14 15:08:13 -0700376// if item != NULL, it's the item we just inserted
377// true == more items eligible to be recovered
Andy Hungf7c14102020-04-18 14:54:08 -0700378bool MediaMetricsService::expirations(const std::shared_ptr<const mediametrics::Item>& item)
Ray Essick92d23b42018-01-29 12:10:30 -0800379{
Ray Essick72a436b2018-06-14 15:08:13 -0700380 bool more = false;
Ray Essicke5db6db2017-11-10 15:54:32 -0800381
Andy Hung17dbaf22019-10-11 14:06:31 -0700382 // check queue size
383 size_t overlimit = 0;
384 if (mMaxRecords > 0 && mItems.size() > mMaxRecords) {
385 overlimit = mItems.size() - mMaxRecords;
386 if (overlimit > mMaxRecordsExpiredAtOnce) {
387 more = true;
388 overlimit = mMaxRecordsExpiredAtOnce;
Ray Essickf65f4212017-08-31 11:41:19 -0700389 }
390 }
391
Andy Hung17dbaf22019-10-11 14:06:31 -0700392 // check queue times
393 size_t expired = 0;
394 if (!more && mMaxRecordAgeNs > 0) {
395 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
396 // we check one at a time, skip search would be more efficient.
397 size_t i = overlimit;
398 for (; i < mItems.size(); ++i) {
399 auto &oitem = mItems[i];
Ray Essickf65f4212017-08-31 11:41:19 -0700400 nsecs_t when = oitem->getTimestamp();
Andy Hung82a074b2019-12-03 14:16:45 -0800401 if (oitem.get() == item.get()) {
Ray Essicke5db6db2017-11-10 15:54:32 -0800402 break;
403 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700404 if (now > when && (now - when) <= mMaxRecordAgeNs) {
Andy Hunged416da2020-03-05 18:42:55 -0800405 break; // Note SYSTEM_TIME_REALTIME may not be monotonic.
Ray Essickf65f4212017-08-31 11:41:19 -0700406 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700407 if (i >= mMaxRecordsExpiredAtOnce) {
Ray Essick72a436b2018-06-14 15:08:13 -0700408 // this represents "one too many"; tell caller there are
409 // more to be reclaimed.
410 more = true;
411 break;
412 }
Ray Essick3938dc62016-11-01 08:56:56 -0700413 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700414 expired = i - overlimit;
Ray Essick3938dc62016-11-01 08:56:56 -0700415 }
Ray Essick72a436b2018-06-14 15:08:13 -0700416
Andy Hung17dbaf22019-10-11 14:06:31 -0700417 if (const size_t toErase = overlimit + expired;
418 toErase > 0) {
419 mItemsDiscardedCount += overlimit;
420 mItemsDiscardedExpire += expired;
421 mItemsDiscarded += toErase;
422 mItems.erase(mItems.begin(), mItems.begin() + toErase); // erase from front
423 }
Ray Essick72a436b2018-06-14 15:08:13 -0700424 return more;
425}
426
Ray Essickf27e9872019-12-07 06:28:46 -0800427void MediaMetricsService::processExpirations()
Ray Essick72a436b2018-06-14 15:08:13 -0700428{
429 bool more;
430 do {
431 sleep(1);
Andy Hung17dbaf22019-10-11 14:06:31 -0700432 std::lock_guard _l(mLock);
Andy Hungf7c14102020-04-18 14:54:08 -0700433 more = expirations(nullptr);
Ray Essick72a436b2018-06-14 15:08:13 -0700434 } while (more);
Ray Essick72a436b2018-06-14 15:08:13 -0700435}
436
Ray Essickf27e9872019-12-07 06:28:46 -0800437void MediaMetricsService::saveItem(const std::shared_ptr<const mediametrics::Item>& item)
Ray Essick72a436b2018-06-14 15:08:13 -0700438{
Andy Hung17dbaf22019-10-11 14:06:31 -0700439 std::lock_guard _l(mLock);
440 // we assume the items are roughly in time order.
441 mItems.emplace_back(item);
442 ++mItemsFinalized;
Andy Hungf7c14102020-04-18 14:54:08 -0700443 if (expirations(item)
Andy Hung17dbaf22019-10-11 14:06:31 -0700444 && (!mExpireFuture.valid()
445 || mExpireFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready)) {
446 mExpireFuture = std::async(std::launch::async, [this] { processExpirations(); });
Ray Essick72a436b2018-06-14 15:08:13 -0700447 }
Ray Essick3938dc62016-11-01 08:56:56 -0700448}
449
Andy Hung17dbaf22019-10-11 14:06:31 -0700450/* static */
Ray Essickf27e9872019-12-07 06:28:46 -0800451bool MediaMetricsService::isContentValid(const mediametrics::Item *item, bool isTrusted)
Ray Essickd38e1742017-01-23 15:17:06 -0800452{
Andy Hung17dbaf22019-10-11 14:06:31 -0700453 if (isTrusted) return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800454 // untrusted uids can only send us a limited set of keys
Andy Hung17dbaf22019-10-11 14:06:31 -0700455 const std::string &key = item->getKey();
Andy Hung06f3aba2019-12-03 16:36:42 -0800456 if (startsWith(key, "audio.")) return true;
Edwin Wong8d188352020-02-11 11:59:34 -0800457 if (startsWith(key, "drm.vendor.")) return true;
458 // the list of allowedKey uses statsd_handlers
459 // in iface_statsd.cpp as reference
460 // drmmanager is from a trusted uid, therefore not needed here
Andy Hung17dbaf22019-10-11 14:06:31 -0700461 for (const char *allowedKey : {
Andy Hung06f3aba2019-12-03 16:36:42 -0800462 // legacy audio
Andy Hung17dbaf22019-10-11 14:06:31 -0700463 "audiopolicy",
464 "audiorecord",
465 "audiothread",
466 "audiotrack",
Andy Hung06f3aba2019-12-03 16:36:42 -0800467 // other media
Andy Hung17dbaf22019-10-11 14:06:31 -0700468 "codec",
469 "extractor",
Edwin Wong8d188352020-02-11 11:59:34 -0800470 "mediadrm",
Santiago Seifertf7022f22020-08-07 13:48:45 +0100471 "mediaparser",
Andy Hung17dbaf22019-10-11 14:06:31 -0700472 "nuplayer",
473 }) {
474 if (key == allowedKey) {
475 return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800476 }
477 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700478 ALOGD("%s: invalid key: %s", __func__, item->toString().c_str());
Ray Essick3938dc62016-11-01 08:56:56 -0700479 return false;
480}
481
Andy Hung17dbaf22019-10-11 14:06:31 -0700482// are we rate limited, normally false
Ray Essickf27e9872019-12-07 06:28:46 -0800483bool MediaMetricsService::isRateLimited(mediametrics::Item *) const
Andy Hung17dbaf22019-10-11 14:06:31 -0700484{
485 return false;
486}
487
Ray Essick3938dc62016-11-01 08:56:56 -0700488} // namespace android