blob: 9d380ec1709b6653ff6ba3064f44f322ab13d89b [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
Andy Hung49ca44e2020-11-10 22:14:58 -080028#include <binder/IServiceManager.h> // checkCallingPermission
Andy Hung17dbaf22019-10-11 14:06:31 -070029#include <cutils/properties.h> // for property_get
Andy Hung9099a1a2020-04-04 14:23:36 -070030#include <mediautils/MemoryLeakTrackUtil.h>
31#include <memunreachable/memunreachable.h>
Andy Hung17dbaf22019-10-11 14:06:31 -070032#include <private/android_filesystem_config.h> // UID
33
Ray Essick3938dc62016-11-01 08:56:56 -070034namespace android {
35
Andy Hung3ab1b322020-05-18 10:47:31 -070036using mediametrics::Item;
37using mediametrics::startsWith;
Andy Hung1efc9c62019-12-03 13:43:33 -080038
Ray Essickf65f4212017-08-31 11:41:19 -070039// individual records kept in memory: age or count
Ray Essick72a436b2018-06-14 15:08:13 -070040// age: <= 28 hours (1 1/6 days)
Ray Essickf65f4212017-08-31 11:41:19 -070041// count: hard limit of # records
42// (0 for either of these disables that threshold)
Ray Essick72a436b2018-06-14 15:08:13 -070043//
Andy Hung17dbaf22019-10-11 14:06:31 -070044static constexpr nsecs_t kMaxRecordAgeNs = 28 * 3600 * NANOS_PER_SECOND;
Ray Essick23f4d6c2019-06-20 10:16:37 -070045// 2019/6: average daily per device is currently 375-ish;
46// setting this to 2000 is large enough to catch most devices
47// we'll lose some data on very very media-active devices, but only for
48// the gms collection; statsd will have already covered those for us.
49// This also retains enough information to help with bugreports
Andy Hung17dbaf22019-10-11 14:06:31 -070050static constexpr size_t kMaxRecords = 2000;
Ray Essick72a436b2018-06-14 15:08:13 -070051
52// max we expire in a single call, to constrain how long we hold the
53// mutex, which also constrains how long a client might wait.
Andy Hung17dbaf22019-10-11 14:06:31 -070054static constexpr size_t kMaxExpiredAtOnce = 50;
Ray Essick72a436b2018-06-14 15:08:13 -070055
56// TODO: need to look at tuning kMaxRecords and friends for low-memory devices
Ray Essick2e9c63b2017-03-29 15:16:44 -070057
Andy Hung55aaf522019-12-03 15:07:51 -080058/* static */
Ray Essickf27e9872019-12-07 06:28:46 -080059nsecs_t MediaMetricsService::roundTime(nsecs_t timeNs)
Andy Hung55aaf522019-12-03 15:07:51 -080060{
61 return (timeNs + NANOS_PER_SECOND / 2) / NANOS_PER_SECOND * NANOS_PER_SECOND;
62}
63
Andy Hunga85efab2019-12-23 11:41:29 -080064/* static */
65bool MediaMetricsService::useUidForPackage(
66 const std::string& package, const std::string& installer)
67{
Andy Hung3ab1b322020-05-18 10:47:31 -070068 if (strchr(package.c_str(), '.') == nullptr) {
Andy Hunga85efab2019-12-23 11:41:29 -080069 return false; // not of form 'com.whatever...'; assume internal and ok
70 } else if (strncmp(package.c_str(), "android.", 8) == 0) {
71 return false; // android.* packages are assumed fine
72 } else if (strncmp(installer.c_str(), "com.android.", 12) == 0) {
73 return false; // from play store
74 } else if (strncmp(installer.c_str(), "com.google.", 11) == 0) {
75 return false; // some google source
76 } else if (strcmp(installer.c_str(), "preload") == 0) {
77 return false; // preloads
78 } else {
79 return true; // we're not sure where it came from, use uid only.
80 }
81}
82
Andy Hungce9b6632020-04-28 20:15:17 -070083/* static */
84std::pair<std::string, int64_t>
85MediaMetricsService::getSanitizedPackageNameAndVersionCode(uid_t uid) {
86 // Meyer's singleton, initialized on first access.
87 // mUidInfo is locked internally.
88 static mediautils::UidInfo uidInfo;
89
90 // get info.
91 mediautils::UidInfo::Info info = uidInfo.getInfo(uid);
92 if (useUidForPackage(info.package, info.installer)) {
93 return { std::to_string(uid), /* versionCode */ 0 };
94 } else {
95 return { info.package, info.versionCode };
96 }
97}
98
Ray Essickf27e9872019-12-07 06:28:46 -080099MediaMetricsService::MediaMetricsService()
Ray Essick2e9c63b2017-03-29 15:16:44 -0700100 : mMaxRecords(kMaxRecords),
Ray Essickf65f4212017-08-31 11:41:19 -0700101 mMaxRecordAgeNs(kMaxRecordAgeNs),
Andy Hung3b4c1f02020-01-23 18:58:32 -0800102 mMaxRecordsExpiredAtOnce(kMaxExpiredAtOnce)
Andy Hung17dbaf22019-10-11 14:06:31 -0700103{
104 ALOGD("%s", __func__);
Ray Essick3938dc62016-11-01 08:56:56 -0700105}
106
Ray Essickf27e9872019-12-07 06:28:46 -0800107MediaMetricsService::~MediaMetricsService()
Andy Hung17dbaf22019-10-11 14:06:31 -0700108{
109 ALOGD("%s", __func__);
110 // the class destructor clears anyhow, but we enforce clearing items first.
111 mItemsDiscarded += mItems.size();
112 mItems.clear();
Ray Essick3938dc62016-11-01 08:56:56 -0700113}
114
Ray Essickf27e9872019-12-07 06:28:46 -0800115status_t MediaMetricsService::submitInternal(mediametrics::Item *item, bool release)
Ray Essick92d23b42018-01-29 12:10:30 -0800116{
Andy Hung55aaf522019-12-03 15:07:51 -0800117 // calling PID is 0 for one-way calls.
118 const pid_t pid = IPCThreadState::self()->getCallingPid();
119 const pid_t pid_given = item->getPid();
120 const uid_t uid = IPCThreadState::self()->getCallingUid();
121 const uid_t uid_given = item->getUid();
Ray Essickd38e1742017-01-23 15:17:06 -0800122
Andy Hung55aaf522019-12-03 15:07:51 -0800123 //ALOGD("%s: caller pid=%d uid=%d, item pid=%d uid=%d", __func__,
124 // (int)pid, (int)uid, (int) pid_given, (int)uid_given);
Ray Essickd38e1742017-01-23 15:17:06 -0800125
Andy Hung17dbaf22019-10-11 14:06:31 -0700126 bool isTrusted;
127 switch (uid) {
Andy Hung55aaf522019-12-03 15:07:51 -0800128 case AID_AUDIOSERVER:
129 case AID_BLUETOOTH:
130 case AID_CAMERA:
Andy Hung17dbaf22019-10-11 14:06:31 -0700131 case AID_DRM:
132 case AID_MEDIA:
133 case AID_MEDIA_CODEC:
134 case AID_MEDIA_EX:
135 case AID_MEDIA_DRM:
Andy Hung5d3f2d12020-03-04 19:55:03 -0800136 // case AID_SHELL: // DEBUG ONLY - used for mediametrics_tests to add new keys
Andy Hung55aaf522019-12-03 15:07:51 -0800137 case AID_SYSTEM:
Andy Hung17dbaf22019-10-11 14:06:31 -0700138 // trusted source, only override default values
139 isTrusted = true;
Andy Hung55aaf522019-12-03 15:07:51 -0800140 if (uid_given == (uid_t)-1) {
Ray Essickd38e1742017-01-23 15:17:06 -0800141 item->setUid(uid);
Andy Hung17dbaf22019-10-11 14:06:31 -0700142 }
Andy Hung55aaf522019-12-03 15:07:51 -0800143 if (pid_given == (pid_t)-1) {
144 item->setPid(pid); // if one-way then this is 0.
Andy Hung17dbaf22019-10-11 14:06:31 -0700145 }
146 break;
147 default:
148 isTrusted = false;
Andy Hung55aaf522019-12-03 15:07:51 -0800149 item->setPid(pid); // always use calling pid, if one-way then this is 0.
Andy Hung17dbaf22019-10-11 14:06:31 -0700150 item->setUid(uid);
151 break;
Ray Essickd38e1742017-01-23 15:17:06 -0800152 }
153
Andy Hunga85efab2019-12-23 11:41:29 -0800154 // Overwrite package name and version if the caller was untrusted or empty
155 if (!isTrusted || item->getPkgName().empty()) {
Andy Hung3ab1b322020-05-18 10:47:31 -0700156 const uid_t uidItem = item->getUid();
Andy Hungce9b6632020-04-28 20:15:17 -0700157 const auto [ pkgName, version ] =
Andy Hung3ab1b322020-05-18 10:47:31 -0700158 MediaMetricsService::getSanitizedPackageNameAndVersionCode(uidItem);
Andy Hungce9b6632020-04-28 20:15:17 -0700159 item->setPkgName(pkgName);
160 item->setPkgVersionCode(version);
Adam Stone21c72122017-09-05 19:02:06 -0700161 }
162
Andy Hung5d3f2d12020-03-04 19:55:03 -0800163 ALOGV("%s: isTrusted:%d given uid %d; sanitized uid: %d sanitized pkg: %s "
Andy Hung17dbaf22019-10-11 14:06:31 -0700164 "sanitized pkg version: %lld",
165 __func__,
Andy Hung5d3f2d12020-03-04 19:55:03 -0800166 (int)isTrusted,
Adam Stone21c72122017-09-05 19:02:06 -0700167 uid_given, item->getUid(),
168 item->getPkgName().c_str(),
Andy Hung17dbaf22019-10-11 14:06:31 -0700169 (long long)item->getPkgVersionCode());
Ray Essick3938dc62016-11-01 08:56:56 -0700170
171 mItemsSubmitted++;
172
173 // validate the record; we discard if we don't like it
Andy Hung17dbaf22019-10-11 14:06:31 -0700174 if (isContentValid(item, isTrusted) == false) {
Andy Hunga87e69c2019-10-18 10:07:40 -0700175 if (release) delete item;
176 return PERMISSION_DENIED;
Ray Essick3938dc62016-11-01 08:56:56 -0700177 }
178
Ray Essick92d23b42018-01-29 12:10:30 -0800179 // XXX: if we have a sessionid in the new record, look to make
Ray Essick3938dc62016-11-01 08:56:56 -0700180 // sure it doesn't appear in the finalized list.
Ray Essick3938dc62016-11-01 08:56:56 -0700181
Ray Essick92d23b42018-01-29 12:10:30 -0800182 if (item->count() == 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700183 ALOGV("%s: dropping empty record...", __func__);
Andy Hunga87e69c2019-10-18 10:07:40 -0700184 if (release) delete item;
185 return BAD_VALUE;
Ray Essick3938dc62016-11-01 08:56:56 -0700186 }
Ray Essick92d23b42018-01-29 12:10:30 -0800187
Andy Hung55aaf522019-12-03 15:07:51 -0800188 if (!isTrusted || item->getTimestamp() == 0) {
Muhammad Qureshi087b37c2020-06-16 16:37:36 -0700189 // Statsd logs two times for events: ElapsedRealTimeNs (BOOTTIME) and
Andy Hung3b4c1f02020-01-23 18:58:32 -0800190 // WallClockTimeNs (REALTIME), but currently logs REALTIME to cloud.
Andy Hung55aaf522019-12-03 15:07:51 -0800191 //
Andy Hung3b4c1f02020-01-23 18:58:32 -0800192 // For consistency and correlation with other logging mechanisms
193 // we use REALTIME here.
194 const int64_t now = systemTime(SYSTEM_TIME_REALTIME);
Andy Hung55aaf522019-12-03 15:07:51 -0800195 item->setTimestamp(now);
196 }
197
Andy Hung82a074b2019-12-03 14:16:45 -0800198 // now attach either the item or its dup to a const shared pointer
Ray Essickf27e9872019-12-07 06:28:46 -0800199 std::shared_ptr<const mediametrics::Item> sitem(release ? item : item->dup());
Ray Essick6ce27e52019-02-15 10:58:05 -0800200
Andy Hung06f3aba2019-12-03 16:36:42 -0800201 (void)mAudioAnalytics.submit(sitem, isTrusted);
202
Ray Essickf27e9872019-12-07 06:28:46 -0800203 extern bool dump2Statsd(const std::shared_ptr<const mediametrics::Item>& item);
Andy Hung82a074b2019-12-03 14:16:45 -0800204 (void)dump2Statsd(sitem); // failure should be logged in function.
205 saveItem(sitem);
Andy Hunga87e69c2019-10-18 10:07:40 -0700206 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700207}
208
Ray Essickf27e9872019-12-07 06:28:46 -0800209status_t MediaMetricsService::dump(int fd, const Vector<String16>& args)
Ray Essick3938dc62016-11-01 08:56:56 -0700210{
Ray Essick3938dc62016-11-01 08:56:56 -0700211 String8 result;
212
213 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700214 result.appendFormat("Permission Denial: "
Ray Essickf27e9872019-12-07 06:28:46 -0800215 "can't dump MediaMetricsService from pid=%d, uid=%d\n",
Ray Essick3938dc62016-11-01 08:56:56 -0700216 IPCThreadState::self()->getCallingPid(),
217 IPCThreadState::self()->getCallingUid());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800218 write(fd, result.string(), result.size());
219 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700220 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800221
Andy Hung709b91e2020-04-04 14:23:36 -0700222 static const String16 allOption("--all");
223 static const String16 clearOption("--clear");
Andy Hung9099a1a2020-04-04 14:23:36 -0700224 static const String16 heapOption("--heap");
Andy Hung709b91e2020-04-04 14:23:36 -0700225 static const String16 helpOption("--help");
226 static const String16 prefixOption("--prefix");
227 static const String16 sinceOption("--since");
Andy Hung9099a1a2020-04-04 14:23:36 -0700228 static const String16 unreachableOption("--unreachable");
Andy Hung709b91e2020-04-04 14:23:36 -0700229
230 bool all = false;
231 bool clear = false;
Andy Hung9099a1a2020-04-04 14:23:36 -0700232 bool heap = false;
233 bool unreachable = false;
Andy Hung709b91e2020-04-04 14:23:36 -0700234 int64_t sinceNs = 0;
235 std::string prefix;
Andy Hung9099a1a2020-04-04 14:23:36 -0700236
Andy Hung709b91e2020-04-04 14:23:36 -0700237 const size_t n = args.size();
238 for (size_t i = 0; i < n; i++) {
239 if (args[i] == allOption) {
240 all = true;
241 } else if (args[i] == clearOption) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800242 clear = true;
Andy Hung9099a1a2020-04-04 14:23:36 -0700243 } else if (args[i] == heapOption) {
244 heap = true;
Ray Essick35ad27f2017-01-30 14:04:11 -0800245 } else if (args[i] == helpOption) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700246 // TODO: consider function area dumping.
247 // dumpsys media.metrics audiotrack,codec
248 // or dumpsys media.metrics audiotrack codec
249
Ray Essick35ad27f2017-01-30 14:04:11 -0800250 result.append("Recognized parameters:\n");
Andy Hung709b91e2020-04-04 14:23:36 -0700251 result.append("--all show all records\n");
252 result.append("--clear clear out saved records\n");
253 result.append("--heap show heap usage (top 100)\n");
254 result.append("--help display help\n");
255 result.append("--prefix X process records for component X\n");
256 result.append("--since X X < 0: records from -X seconds in the past\n");
257 result.append(" X = 0: ignore\n");
258 result.append(" X > 0: records from X seconds since Unix epoch\n");
259 result.append("--unreachable show unreachable memory (leaks)\n");
Ray Essick35ad27f2017-01-30 14:04:11 -0800260 write(fd, result.string(), result.size());
261 return NO_ERROR;
Andy Hung709b91e2020-04-04 14:23:36 -0700262 } else if (args[i] == prefixOption) {
263 ++i;
264 if (i < n) {
265 prefix = String8(args[i]).string();
266 }
267 } else if (args[i] == sinceOption) {
268 ++i;
269 if (i < n) {
270 String8 value(args[i]);
271 char *endp;
272 const char *p = value.string();
Andy Hung3ab1b322020-05-18 10:47:31 -0700273 const auto sec = (int64_t)strtoll(p, &endp, 10);
Andy Hung709b91e2020-04-04 14:23:36 -0700274 if (endp == p || *endp != '\0' || sec == 0) {
275 sinceNs = 0;
276 } else if (sec < 0) {
277 sinceNs = systemTime(SYSTEM_TIME_REALTIME) + sec * NANOS_PER_SECOND;
278 } else {
279 sinceNs = sec * NANOS_PER_SECOND;
280 }
281 }
Andy Hung9099a1a2020-04-04 14:23:36 -0700282 } else if (args[i] == unreachableOption) {
283 unreachable = true;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800284 }
285 }
286
Andy Hung17dbaf22019-10-11 14:06:31 -0700287 {
288 std::lock_guard _l(mLock);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800289
Andy Hung17dbaf22019-10-11 14:06:31 -0700290 if (clear) {
291 mItemsDiscarded += mItems.size();
292 mItems.clear();
Andy Hung709b91e2020-04-04 14:23:36 -0700293 mAudioAnalytics.clear();
294 } else {
295 result.appendFormat("Dump of the %s process:\n", kServiceName);
296 const char *prefixptr = prefix.size() > 0 ? prefix.c_str() : nullptr;
Andy Hungf7c14102020-04-18 14:54:08 -0700297 dumpHeaders(result, sinceNs, prefixptr);
298 dumpQueue(result, sinceNs, prefixptr);
Andy Hung709b91e2020-04-04 14:23:36 -0700299
300 // TODO: maybe consider a better way of dumping audio analytics info.
301 const int32_t linesToDump = all ? INT32_MAX : 1000;
302 auto [ dumpString, lines ] = mAudioAnalytics.dump(linesToDump, sinceNs, prefixptr);
303 result.append(dumpString.c_str());
304 if (lines == linesToDump) {
305 result.append("-- some lines may be truncated --\n");
306 }
Andy Hung0f7ad8c2020-01-03 13:24:34 -0800307 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700308 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700309 write(fd, result.string(), result.size());
Andy Hung9099a1a2020-04-04 14:23:36 -0700310
311 // Check heap and unreachable memory outside of lock.
312 if (heap) {
313 dprintf(fd, "\nDumping heap:\n");
314 std::string s = dumpMemoryAddresses(100 /* limit */);
315 write(fd, s.c_str(), s.size());
316 }
317 if (unreachable) {
318 dprintf(fd, "\nDumping unreachable memory:\n");
319 // TODO - should limit be an argument parameter?
320 std::string s = GetUnreachableMemoryString(true /* contents */, 100 /* limit */);
321 write(fd, s.c_str(), s.size());
322 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700323 return NO_ERROR;
324}
325
326// dump headers
Andy Hungf7c14102020-04-18 14:54:08 -0700327void MediaMetricsService::dumpHeaders(String8 &result, int64_t sinceNs, const char* prefix)
Ray Essick92d23b42018-01-29 12:10:30 -0800328{
Ray Essickf27e9872019-12-07 06:28:46 -0800329 if (mediametrics::Item::isEnabled()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700330 result.append("Metrics gathering: enabled\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800331 } else {
Andy Hung17dbaf22019-10-11 14:06:31 -0700332 result.append("Metrics gathering: DISABLED via property\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800333 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700334 result.appendFormat(
335 "Since Boot: Submissions: %lld Accepted: %lld\n",
336 (long long)mItemsSubmitted.load(), (long long)mItemsFinalized);
337 result.appendFormat(
338 "Records Discarded: %lld (by Count: %lld by Expiration: %lld)\n",
339 (long long)mItemsDiscarded, (long long)mItemsDiscardedCount,
340 (long long)mItemsDiscardedExpire);
Andy Hung709b91e2020-04-04 14:23:36 -0700341 if (prefix != nullptr) {
342 result.appendFormat("Restricting to prefix %s", prefix);
343 }
344 if (sinceNs != 0) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700345 result.appendFormat(
346 "Emitting Queue entries more recent than: %lld\n",
Andy Hung709b91e2020-04-04 14:23:36 -0700347 (long long)sinceNs);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800348 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700349}
350
Andy Hung709b91e2020-04-04 14:23:36 -0700351// TODO: should prefix be a set<string>?
Andy Hungf7c14102020-04-18 14:54:08 -0700352void MediaMetricsService::dumpQueue(String8 &result, int64_t sinceNs, const char* prefix)
Ray Essick92d23b42018-01-29 12:10:30 -0800353{
Ray Essick92d23b42018-01-29 12:10:30 -0800354 if (mItems.empty()) {
Andy Hung17dbaf22019-10-11 14:06:31 -0700355 result.append("empty\n");
Andy Hung709b91e2020-04-04 14:23:36 -0700356 return;
357 }
358
359 int slot = 0;
360 for (const auto &item : mItems) { // TODO: consider std::lower_bound() on mItems
361 if (item->getTimestamp() < sinceNs) { // sinceNs == 0 means all items shown
362 continue;
Ray Essick3938dc62016-11-01 08:56:56 -0700363 }
Andy Hung709b91e2020-04-04 14:23:36 -0700364 if (prefix != nullptr && !startsWith(item->getKey(), prefix)) {
365 ALOGV("%s: omit '%s', it's not '%s'",
366 __func__, item->getKey().c_str(), prefix);
367 continue;
368 }
369 result.appendFormat("%5d: %s\n", slot, item->toString().c_str());
370 slot++;
Ray Essick3938dc62016-11-01 08:56:56 -0700371 }
Ray Essick3938dc62016-11-01 08:56:56 -0700372}
373
374//
375// Our Cheap in-core, non-persistent records management.
Ray Essick3938dc62016-11-01 08:56:56 -0700376
Ray Essick72a436b2018-06-14 15:08:13 -0700377// if item != NULL, it's the item we just inserted
378// true == more items eligible to be recovered
Andy Hungf7c14102020-04-18 14:54:08 -0700379bool MediaMetricsService::expirations(const std::shared_ptr<const mediametrics::Item>& item)
Ray Essick92d23b42018-01-29 12:10:30 -0800380{
Ray Essick72a436b2018-06-14 15:08:13 -0700381 bool more = false;
Ray Essicke5db6db2017-11-10 15:54:32 -0800382
Andy Hung17dbaf22019-10-11 14:06:31 -0700383 // check queue size
384 size_t overlimit = 0;
385 if (mMaxRecords > 0 && mItems.size() > mMaxRecords) {
386 overlimit = mItems.size() - mMaxRecords;
387 if (overlimit > mMaxRecordsExpiredAtOnce) {
388 more = true;
389 overlimit = mMaxRecordsExpiredAtOnce;
Ray Essickf65f4212017-08-31 11:41:19 -0700390 }
391 }
392
Andy Hung17dbaf22019-10-11 14:06:31 -0700393 // check queue times
394 size_t expired = 0;
395 if (!more && mMaxRecordAgeNs > 0) {
396 const nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
397 // we check one at a time, skip search would be more efficient.
398 size_t i = overlimit;
399 for (; i < mItems.size(); ++i) {
400 auto &oitem = mItems[i];
Ray Essickf65f4212017-08-31 11:41:19 -0700401 nsecs_t when = oitem->getTimestamp();
Andy Hung82a074b2019-12-03 14:16:45 -0800402 if (oitem.get() == item.get()) {
Ray Essicke5db6db2017-11-10 15:54:32 -0800403 break;
404 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700405 if (now > when && (now - when) <= mMaxRecordAgeNs) {
Andy Hunged416da2020-03-05 18:42:55 -0800406 break; // Note SYSTEM_TIME_REALTIME may not be monotonic.
Ray Essickf65f4212017-08-31 11:41:19 -0700407 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700408 if (i >= mMaxRecordsExpiredAtOnce) {
Ray Essick72a436b2018-06-14 15:08:13 -0700409 // this represents "one too many"; tell caller there are
410 // more to be reclaimed.
411 more = true;
412 break;
413 }
Ray Essick3938dc62016-11-01 08:56:56 -0700414 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700415 expired = i - overlimit;
Ray Essick3938dc62016-11-01 08:56:56 -0700416 }
Ray Essick72a436b2018-06-14 15:08:13 -0700417
Andy Hung17dbaf22019-10-11 14:06:31 -0700418 if (const size_t toErase = overlimit + expired;
419 toErase > 0) {
420 mItemsDiscardedCount += overlimit;
421 mItemsDiscardedExpire += expired;
422 mItemsDiscarded += toErase;
423 mItems.erase(mItems.begin(), mItems.begin() + toErase); // erase from front
424 }
Ray Essick72a436b2018-06-14 15:08:13 -0700425 return more;
426}
427
Ray Essickf27e9872019-12-07 06:28:46 -0800428void MediaMetricsService::processExpirations()
Ray Essick72a436b2018-06-14 15:08:13 -0700429{
430 bool more;
431 do {
432 sleep(1);
Andy Hung17dbaf22019-10-11 14:06:31 -0700433 std::lock_guard _l(mLock);
Andy Hungf7c14102020-04-18 14:54:08 -0700434 more = expirations(nullptr);
Ray Essick72a436b2018-06-14 15:08:13 -0700435 } while (more);
Ray Essick72a436b2018-06-14 15:08:13 -0700436}
437
Ray Essickf27e9872019-12-07 06:28:46 -0800438void MediaMetricsService::saveItem(const std::shared_ptr<const mediametrics::Item>& item)
Ray Essick72a436b2018-06-14 15:08:13 -0700439{
Andy Hung17dbaf22019-10-11 14:06:31 -0700440 std::lock_guard _l(mLock);
441 // we assume the items are roughly in time order.
442 mItems.emplace_back(item);
443 ++mItemsFinalized;
Andy Hungf7c14102020-04-18 14:54:08 -0700444 if (expirations(item)
Andy Hung17dbaf22019-10-11 14:06:31 -0700445 && (!mExpireFuture.valid()
446 || mExpireFuture.wait_for(std::chrono::seconds(0)) == std::future_status::ready)) {
447 mExpireFuture = std::async(std::launch::async, [this] { processExpirations(); });
Ray Essick72a436b2018-06-14 15:08:13 -0700448 }
Ray Essick3938dc62016-11-01 08:56:56 -0700449}
450
Andy Hung17dbaf22019-10-11 14:06:31 -0700451/* static */
Ray Essickf27e9872019-12-07 06:28:46 -0800452bool MediaMetricsService::isContentValid(const mediametrics::Item *item, bool isTrusted)
Ray Essickd38e1742017-01-23 15:17:06 -0800453{
Andy Hung17dbaf22019-10-11 14:06:31 -0700454 if (isTrusted) return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800455 // untrusted uids can only send us a limited set of keys
Andy Hung17dbaf22019-10-11 14:06:31 -0700456 const std::string &key = item->getKey();
Andy Hung06f3aba2019-12-03 16:36:42 -0800457 if (startsWith(key, "audio.")) return true;
Edwin Wong8d188352020-02-11 11:59:34 -0800458 if (startsWith(key, "drm.vendor.")) return true;
459 // the list of allowedKey uses statsd_handlers
460 // in iface_statsd.cpp as reference
461 // drmmanager is from a trusted uid, therefore not needed here
Andy Hung17dbaf22019-10-11 14:06:31 -0700462 for (const char *allowedKey : {
Andy Hung06f3aba2019-12-03 16:36:42 -0800463 // legacy audio
Andy Hung17dbaf22019-10-11 14:06:31 -0700464 "audiopolicy",
465 "audiorecord",
466 "audiothread",
467 "audiotrack",
Andy Hung06f3aba2019-12-03 16:36:42 -0800468 // other media
Andy Hung17dbaf22019-10-11 14:06:31 -0700469 "codec",
470 "extractor",
Edwin Wong8d188352020-02-11 11:59:34 -0800471 "mediadrm",
Santiago Seifert49fb4522020-08-07 13:48:45 +0100472 "mediaparser",
Andy Hung17dbaf22019-10-11 14:06:31 -0700473 "nuplayer",
474 }) {
475 if (key == allowedKey) {
476 return true;
Ray Essickd38e1742017-01-23 15:17:06 -0800477 }
478 }
Andy Hung17dbaf22019-10-11 14:06:31 -0700479 ALOGD("%s: invalid key: %s", __func__, item->toString().c_str());
Ray Essick3938dc62016-11-01 08:56:56 -0700480 return false;
481}
482
Andy Hung17dbaf22019-10-11 14:06:31 -0700483// are we rate limited, normally false
Ray Essickf27e9872019-12-07 06:28:46 -0800484bool MediaMetricsService::isRateLimited(mediametrics::Item *) const
Andy Hung17dbaf22019-10-11 14:06:31 -0700485{
486 return false;
487}
488
Ray Essick3938dc62016-11-01 08:56:56 -0700489} // namespace android