blob: 3c398834535657aaf30b1ca249e5415981045df5 [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
17// Proxy for media player implementations
18
19//#define LOG_NDEBUG 0
20#define LOG_TAG "MediaAnalyticsService"
21#include <utils/Log.h>
22
Ray Essick2e9c63b2017-03-29 15:16:44 -070023#include <stdint.h>
Ray Essick3938dc62016-11-01 08:56:56 -070024#include <inttypes.h>
25#include <sys/types.h>
26#include <sys/stat.h>
27#include <sys/time.h>
28#include <dirent.h>
29#include <unistd.h>
30
31#include <string.h>
Ray Essickf65f4212017-08-31 11:41:19 -070032#include <pwd.h>
Ray Essick3938dc62016-11-01 08:56:56 -070033
34#include <cutils/atomic.h>
35#include <cutils/properties.h> // for property_get
36
37#include <utils/misc.h>
38
Ray Essickf65f4212017-08-31 11:41:19 -070039#include <android/content/pm/IPackageManagerNative.h>
40
Ray Essick3938dc62016-11-01 08:56:56 -070041#include <binder/IPCThreadState.h>
42#include <binder/IServiceManager.h>
43#include <binder/MemoryHeapBase.h>
44#include <binder/MemoryBase.h>
45#include <gui/Surface.h>
46#include <utils/Errors.h> // for status_t
47#include <utils/List.h>
48#include <utils/String8.h>
49#include <utils/SystemClock.h>
50#include <utils/Timers.h>
51#include <utils/Vector.h>
52
53#include <media/AudioPolicyHelper.h>
54#include <media/IMediaHTTPService.h>
55#include <media/IRemoteDisplay.h>
56#include <media/IRemoteDisplayClient.h>
57#include <media/MediaPlayerInterface.h>
58#include <media/mediarecorder.h>
59#include <media/MediaMetadataRetrieverInterface.h>
60#include <media/Metadata.h>
61#include <media/AudioTrack.h>
62#include <media/MemoryLeakTrackUtil.h>
63#include <media/stagefright/MediaCodecList.h>
64#include <media/stagefright/MediaErrors.h>
65#include <media/stagefright/Utils.h>
66#include <media/stagefright/foundation/ADebug.h>
67#include <media/stagefright/foundation/ALooperRoster.h>
68#include <mediautils/BatteryNotifier.h>
69
70//#include <memunreachable/memunreachable.h>
71#include <system/audio.h>
72
73#include <private/android_filesystem_config.h>
74
75#include "MediaAnalyticsService.h"
76
Ray Essick2e9c63b2017-03-29 15:16:44 -070077#include "MetricsSummarizer.h"
78#include "MetricsSummarizerCodec.h"
79#include "MetricsSummarizerExtractor.h"
80#include "MetricsSummarizerPlayer.h"
81#include "MetricsSummarizerRecorder.h"
82
Ray Essick3938dc62016-11-01 08:56:56 -070083
84namespace android {
85
Ray Essickf65f4212017-08-31 11:41:19 -070086 using namespace android::base;
87 using namespace android::content::pm;
88
Ray Essick3938dc62016-11-01 08:56:56 -070089
Ray Essick2e9c63b2017-03-29 15:16:44 -070090
91// summarized records
Ray Essickf65f4212017-08-31 11:41:19 -070092// up to 36 sets, each covering an hour -- so at least 1.5 days
Ray Essick2e9c63b2017-03-29 15:16:44 -070093// (will be longer if there are hours without any media action)
94static const nsecs_t kNewSetIntervalNs = 3600*(1000*1000*1000ll);
Ray Essickf65f4212017-08-31 11:41:19 -070095static const int kMaxRecordSets = 36;
Ray Essick2e9c63b2017-03-29 15:16:44 -070096
Ray Essickf65f4212017-08-31 11:41:19 -070097// individual records kept in memory: age or count
98// age: <= 36 hours (1.5 days)
99// count: hard limit of # records
100// (0 for either of these disables that threshold)
101static const nsecs_t kMaxRecordAgeNs = 36 * 3600 * (1000*1000*1000ll);
102static const int kMaxRecords = 0;
Ray Essick2e9c63b2017-03-29 15:16:44 -0700103
104static const char *kServiceName = "media.metrics";
105
Ray Essick3938dc62016-11-01 08:56:56 -0700106void MediaAnalyticsService::instantiate() {
107 defaultServiceManager()->addService(
Ray Essick2e9c63b2017-03-29 15:16:44 -0700108 String16(kServiceName), new MediaAnalyticsService());
Ray Essick3938dc62016-11-01 08:56:56 -0700109}
110
Ray Essick2e9c63b2017-03-29 15:16:44 -0700111// handle sets of summarizers
112MediaAnalyticsService::SummarizerSet::SummarizerSet() {
113 mSummarizers = new List<MetricsSummarizer *>();
114}
Ray Essickf65f4212017-08-31 11:41:19 -0700115
Ray Essick2e9c63b2017-03-29 15:16:44 -0700116MediaAnalyticsService::SummarizerSet::~SummarizerSet() {
117 // empty the list
118 List<MetricsSummarizer *> *l = mSummarizers;
119 while (l->size() > 0) {
120 MetricsSummarizer *summarizer = *(l->begin());
121 l->erase(l->begin());
122 delete summarizer;
123 }
124}
125
126void MediaAnalyticsService::newSummarizerSet() {
127 ALOGD("MediaAnalyticsService::newSummarizerSet");
128 MediaAnalyticsService::SummarizerSet *set = new MediaAnalyticsService::SummarizerSet();
129 nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
130 set->setStarted(now);
131
132 set->appendSummarizer(new MetricsSummarizerExtractor("extractor"));
133 set->appendSummarizer(new MetricsSummarizerCodec("codec"));
134 set->appendSummarizer(new MetricsSummarizerPlayer("nuplayer"));
135 set->appendSummarizer(new MetricsSummarizerRecorder("recorder"));
136
137 // ALWAYS at the end, since it catches everything
138 set->appendSummarizer(new MetricsSummarizer(NULL));
139
140 // inject this set at the BACK of the list.
141 mSummarizerSets->push_back(set);
142 mCurrentSet = set;
143
144 // limit the # that we have
145 if (mMaxRecordSets > 0) {
146 List<SummarizerSet *> *l = mSummarizerSets;
147 while (l->size() > (size_t) mMaxRecordSets) {
148 ALOGD("Deleting oldest record set....");
149 MediaAnalyticsService::SummarizerSet *oset = *(l->begin());
150 l->erase(l->begin());
151 delete oset;
152 mSetsDiscarded++;
153 }
154 }
155}
156
Ray Essick3938dc62016-11-01 08:56:56 -0700157MediaAnalyticsService::MediaAnalyticsService()
Ray Essick2e9c63b2017-03-29 15:16:44 -0700158 : mMaxRecords(kMaxRecords),
Ray Essickf65f4212017-08-31 11:41:19 -0700159 mMaxRecordAgeNs(kMaxRecordAgeNs),
Ray Essick2e9c63b2017-03-29 15:16:44 -0700160 mMaxRecordSets(kMaxRecordSets),
Ray Essickf65f4212017-08-31 11:41:19 -0700161 mNewSetInterval(kNewSetIntervalNs),
162 mDumpProto(MediaAnalyticsItem::PROTO_V0) {
Ray Essick3938dc62016-11-01 08:56:56 -0700163
164 ALOGD("MediaAnalyticsService created");
165 // clear our queues
Ray Essickb5fac8e2016-12-12 11:33:56 -0800166 mOpen = new List<MediaAnalyticsItem *>();
167 mFinalized = new List<MediaAnalyticsItem *>();
Ray Essick3938dc62016-11-01 08:56:56 -0700168
Ray Essick2e9c63b2017-03-29 15:16:44 -0700169 mSummarizerSets = new List<MediaAnalyticsService::SummarizerSet *>();
170 newSummarizerSet();
171
Ray Essick3938dc62016-11-01 08:56:56 -0700172 mItemsSubmitted = 0;
173 mItemsFinalized = 0;
174 mItemsDiscarded = 0;
Ray Essickf65f4212017-08-31 11:41:19 -0700175 mItemsDiscardedExpire = 0;
176 mItemsDiscardedCount = 0;
Ray Essick3938dc62016-11-01 08:56:56 -0700177
178 mLastSessionID = 0;
179 // recover any persistency we set up
180 // etc
181}
182
183MediaAnalyticsService::~MediaAnalyticsService() {
184 ALOGD("MediaAnalyticsService destroyed");
185
Ray Essick2e9c63b2017-03-29 15:16:44 -0700186 // clean out mOpen and mFinalized
Ray Essickf65f4212017-08-31 11:41:19 -0700187 while (mOpen->size() > 0) {
188 MediaAnalyticsItem * oitem = *(mOpen->begin());
189 mOpen->erase(mOpen->begin());
190 delete oitem;
191 mItemsDiscarded++;
192 mItemsDiscardedCount++;
193 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700194 delete mOpen;
195 mOpen = NULL;
Ray Essickf65f4212017-08-31 11:41:19 -0700196
197 while (mFinalized->size() > 0) {
198 MediaAnalyticsItem * oitem = *(mFinalized->begin());
199 mFinalized->erase(mFinalized->begin());
200 delete oitem;
201 mItemsDiscarded++;
202 mItemsDiscardedCount++;
203 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700204 delete mFinalized;
205 mFinalized = NULL;
206
207 // XXX: clean out the summaries
Ray Essick3938dc62016-11-01 08:56:56 -0700208}
209
210
211MediaAnalyticsItem::SessionID_t MediaAnalyticsService::generateUniqueSessionID() {
212 // generate a new sessionid
213
214 Mutex::Autolock _l(mLock_ids);
215 return (++mLastSessionID);
216}
217
Ray Essickb5fac8e2016-12-12 11:33:56 -0800218// caller surrenders ownership of 'item'
219MediaAnalyticsItem::SessionID_t MediaAnalyticsService::submit(MediaAnalyticsItem *item, bool forcenew) {
Ray Essick3938dc62016-11-01 08:56:56 -0700220
221 MediaAnalyticsItem::SessionID_t id = MediaAnalyticsItem::SessionIDInvalid;
222
Ray Essickd38e1742017-01-23 15:17:06 -0800223 // we control these, generally not trusting user input
Ray Essick3938dc62016-11-01 08:56:56 -0700224 nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
225 item->setTimestamp(now);
226 int pid = IPCThreadState::self()->getCallingPid();
Ray Essick3938dc62016-11-01 08:56:56 -0700227 int uid = IPCThreadState::self()->getCallingUid();
Ray Essickd38e1742017-01-23 15:17:06 -0800228
229 int uid_given = item->getUid();
230 int pid_given = item->getPid();
231
232 // although we do make exceptions for particular client uids
233 // that we know we trust.
234 //
235 bool isTrusted = false;
236
Ray Essickf65f4212017-08-31 11:41:19 -0700237 ALOGV("caller has uid=%d, embedded uid=%d", uid, uid_given);
238
Ray Essickd38e1742017-01-23 15:17:06 -0800239 switch (uid) {
240 case AID_MEDIA:
241 case AID_MEDIA_CODEC:
242 case AID_MEDIA_EX:
243 case AID_MEDIA_DRM:
244 // trusted source, only override default values
Ray Essickf65f4212017-08-31 11:41:19 -0700245 isTrusted = true;
Ray Essickd38e1742017-01-23 15:17:06 -0800246 if (uid_given == (-1)) {
247 item->setUid(uid);
248 }
249 if (pid_given == (-1)) {
250 item->setPid(pid);
251 }
252 break;
253 default:
254 isTrusted = false;
255 item->setPid(pid);
256 item->setUid(uid);
257 break;
258 }
259
Ray Essickf65f4212017-08-31 11:41:19 -0700260 item->setPkgName(getPkgName(item->getUid(), true));
261 item->setPkgVersionCode(0);
262 ALOGD("info is from uid %d pkg '%s', version %d", item->getUid(), item->getPkgName().c_str(), item->getPkgVersionCode());
Ray Essick3938dc62016-11-01 08:56:56 -0700263
264 mItemsSubmitted++;
265
266 // validate the record; we discard if we don't like it
Ray Essickd38e1742017-01-23 15:17:06 -0800267 if (contentValid(item, isTrusted) == false) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800268 delete item;
Ray Essick3938dc62016-11-01 08:56:56 -0700269 return MediaAnalyticsItem::SessionIDInvalid;
270 }
271
272
273 // if we have a sesisonid in the new record, look to make
274 // sure it doesn't appear in the finalized list.
275 // XXX: this is for security / DOS prevention.
276 // may also require that we persist the unique sessionIDs
277 // across boots [instead of within a single boot]
278
279
280 // match this new record up against records in the open
281 // list...
282 // if there's a match, merge them together
283 // deal with moving the old / merged record into the finalized que
284
285 bool finalizing = item->getFinalized();
286
287 // if finalizing, we'll remove it
Ray Essickb5fac8e2016-12-12 11:33:56 -0800288 MediaAnalyticsItem *oitem = findItem(mOpen, item, finalizing | forcenew);
Ray Essick3938dc62016-11-01 08:56:56 -0700289 if (oitem != NULL) {
290 if (forcenew) {
291 // old one gets finalized, then we insert the new one
292 // so we'll have 2 records at the end of this.
293 // but don't finalize an empty record
Ray Essickb5fac8e2016-12-12 11:33:56 -0800294 if (oitem->count() == 0) {
295 // we're responsible for disposing of the dead record
296 delete oitem;
297 oitem = NULL;
298 } else {
Ray Essick3938dc62016-11-01 08:56:56 -0700299 oitem->setFinalized(true);
Ray Essick2e9c63b2017-03-29 15:16:44 -0700300 summarize(oitem);
Ray Essick3938dc62016-11-01 08:56:56 -0700301 saveItem(mFinalized, oitem, 0);
302 }
303 // new record could itself be marked finalized...
304 if (finalizing) {
Ray Essick2e9c63b2017-03-29 15:16:44 -0700305 summarize(item);
Ray Essick3938dc62016-11-01 08:56:56 -0700306 saveItem(mFinalized, item, 0);
307 mItemsFinalized++;
308 } else {
309 saveItem(mOpen, item, 1);
310 }
311 id = item->getSessionID();
312 } else {
313 // combine the records, send it to finalized if appropriate
314 oitem->merge(item);
315 if (finalizing) {
Ray Essick2e9c63b2017-03-29 15:16:44 -0700316 summarize(oitem);
Ray Essick3938dc62016-11-01 08:56:56 -0700317 saveItem(mFinalized, oitem, 0);
318 mItemsFinalized++;
319 }
320 id = oitem->getSessionID();
Ray Essickb5fac8e2016-12-12 11:33:56 -0800321
322 // we're responsible for disposing of the dead record
323 delete item;
324 item = NULL;
Ray Essick3938dc62016-11-01 08:56:56 -0700325 }
326 } else {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800327 // nothing to merge, save the new record
328 id = item->getSessionID();
329 if (finalizing) {
330 if (item->count() == 0) {
331 // drop empty records
332 delete item;
333 item = NULL;
Ray Essick3938dc62016-11-01 08:56:56 -0700334 } else {
Ray Essick2e9c63b2017-03-29 15:16:44 -0700335 summarize(item);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800336 saveItem(mFinalized, item, 0);
337 mItemsFinalized++;
Ray Essick3938dc62016-11-01 08:56:56 -0700338 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800339 } else {
340 saveItem(mOpen, item, 1);
341 }
Ray Essick3938dc62016-11-01 08:56:56 -0700342 }
Ray Essick3938dc62016-11-01 08:56:56 -0700343 return id;
344}
345
Ray Essickf65f4212017-08-31 11:41:19 -0700346
Ray Essickb5fac8e2016-12-12 11:33:56 -0800347status_t MediaAnalyticsService::dump(int fd, const Vector<String16>& args)
Ray Essick3938dc62016-11-01 08:56:56 -0700348{
Ray Essickb5fac8e2016-12-12 11:33:56 -0800349 const size_t SIZE = 512;
Ray Essick3938dc62016-11-01 08:56:56 -0700350 char buffer[SIZE];
351 String8 result;
352
353 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
354 snprintf(buffer, SIZE, "Permission Denial: "
355 "can't dump MediaAnalyticsService from pid=%d, uid=%d\n",
356 IPCThreadState::self()->getCallingPid(),
357 IPCThreadState::self()->getCallingUid());
358 result.append(buffer);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800359 write(fd, result.string(), result.size());
360 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700361 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800362
363 // crack any parameters
Ray Essick2e9c63b2017-03-29 15:16:44 -0700364 String16 summaryOption("-summary");
Ray Essickf65f4212017-08-31 11:41:19 -0700365 bool summary = false;
366 String16 protoOption("-proto");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800367 String16 clearOption("-clear");
Ray Essickf65f4212017-08-31 11:41:19 -0700368 bool clear = false;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800369 String16 sinceOption("-since");
Ray Essickf65f4212017-08-31 11:41:19 -0700370 nsecs_t ts_since = 0;
Ray Essick35ad27f2017-01-30 14:04:11 -0800371 String16 helpOption("-help");
Ray Essick2e9c63b2017-03-29 15:16:44 -0700372 String16 onlyOption("-only");
Ray Essickf65f4212017-08-31 11:41:19 -0700373 AString only;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800374 int n = args.size();
Ray Essickf65f4212017-08-31 11:41:19 -0700375
Ray Essickb5fac8e2016-12-12 11:33:56 -0800376 for (int i = 0; i < n; i++) {
377 String8 myarg(args[i]);
378 if (args[i] == clearOption) {
379 clear = true;
Ray Essick2e9c63b2017-03-29 15:16:44 -0700380 } else if (args[i] == summaryOption) {
381 summary = true;
Ray Essickf65f4212017-08-31 11:41:19 -0700382 } else if (args[i] == protoOption) {
383 i++;
384 if (i < n) {
385 String8 value(args[i]);
386 int proto = MediaAnalyticsItem::PROTO_V0; // default to original
387 char *endp;
388 const char *p = value.string();
389 proto = strtol(p, &endp, 10);
390 if (endp != p || *endp == '\0') {
391 if (proto < MediaAnalyticsItem::PROTO_FIRST) {
392 proto = MediaAnalyticsItem::PROTO_FIRST;
393 } else if (proto > MediaAnalyticsItem::PROTO_LAST) {
394 proto = MediaAnalyticsItem::PROTO_LAST;
395 }
396 mDumpProto = proto;
397 }
398 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800399 } else if (args[i] == sinceOption) {
400 i++;
401 if (i < n) {
402 String8 value(args[i]);
403 char *endp;
404 const char *p = value.string();
405 ts_since = strtoll(p, &endp, 10);
406 if (endp == p || *endp != '\0') {
407 ts_since = 0;
408 }
409 } else {
410 ts_since = 0;
411 }
Ray Essick35ad27f2017-01-30 14:04:11 -0800412 // command line is milliseconds; internal units are nano-seconds
413 ts_since *= 1000*1000;
Ray Essick2e9c63b2017-03-29 15:16:44 -0700414 } else if (args[i] == onlyOption) {
415 i++;
416 if (i < n) {
417 String8 value(args[i]);
Ray Essickf65f4212017-08-31 11:41:19 -0700418 only = value.string();
Ray Essick2e9c63b2017-03-29 15:16:44 -0700419 }
Ray Essick35ad27f2017-01-30 14:04:11 -0800420 } else if (args[i] == helpOption) {
421 result.append("Recognized parameters:\n");
422 result.append("-help this help message\n");
Ray Essickf65f4212017-08-31 11:41:19 -0700423 result.append("-proto X dump using protocol X (defaults to 1)");
Ray Essick2e9c63b2017-03-29 15:16:44 -0700424 result.append("-summary show summary info\n");
Ray Essick35ad27f2017-01-30 14:04:11 -0800425 result.append("-clear clears out saved records\n");
Ray Essick2e9c63b2017-03-29 15:16:44 -0700426 result.append("-only X process records for component X\n");
427 result.append("-since X include records since X\n");
428 result.append(" (X is milliseconds since the UNIX epoch)\n");
Ray Essick35ad27f2017-01-30 14:04:11 -0800429 write(fd, result.string(), result.size());
430 return NO_ERROR;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800431 }
432 }
433
434 Mutex::Autolock _l(mLock);
435
Ray Essick2e9c63b2017-03-29 15:16:44 -0700436 // we ALWAYS dump this piece
437 snprintf(buffer, SIZE, "Dump of the %s process:\n", kServiceName);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800438 result.append(buffer);
439
Ray Essick2e9c63b2017-03-29 15:16:44 -0700440 dumpHeaders(result, ts_since);
441
Ray Essickf65f4212017-08-31 11:41:19 -0700442 // want exactly 1, to avoid confusing folks that parse the output
Ray Essick2e9c63b2017-03-29 15:16:44 -0700443 if (summary) {
Ray Essickf65f4212017-08-31 11:41:19 -0700444 dumpSummaries(result, ts_since, only.c_str());
Ray Essick2e9c63b2017-03-29 15:16:44 -0700445 } else {
Ray Essickf65f4212017-08-31 11:41:19 -0700446 dumpRecent(result, ts_since, only.c_str());
Ray Essick2e9c63b2017-03-29 15:16:44 -0700447 }
448
449
450 if (clear) {
451 // remove everything from the finalized queue
452 while (mFinalized->size() > 0) {
453 MediaAnalyticsItem * oitem = *(mFinalized->begin());
454 mFinalized->erase(mFinalized->begin());
455 delete oitem;
456 mItemsDiscarded++;
457 }
458
459 // shall we clear the summary data too?
460
461 }
462
463 write(fd, result.string(), result.size());
464 return NO_ERROR;
465}
466
467// dump headers
468void MediaAnalyticsService::dumpHeaders(String8 &result, nsecs_t ts_since) {
469 const size_t SIZE = 512;
470 char buffer[SIZE];
471
Ray Essickf65f4212017-08-31 11:41:19 -0700472 snprintf(buffer, SIZE, "Protocol Version: %d\n", mDumpProto);
473 result.append(buffer);
474
Ray Essickb5fac8e2016-12-12 11:33:56 -0800475 int enabled = MediaAnalyticsItem::isEnabled();
476 if (enabled) {
Ray Essickd38e1742017-01-23 15:17:06 -0800477 snprintf(buffer, SIZE, "Metrics gathering: enabled\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800478 } else {
Ray Essickd38e1742017-01-23 15:17:06 -0800479 snprintf(buffer, SIZE, "Metrics gathering: DISABLED via property\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800480 }
481 result.append(buffer);
482
483 snprintf(buffer, SIZE,
Ray Essickf65f4212017-08-31 11:41:19 -0700484 "Since Boot: Submissions: %8" PRId64
485 " Finalizations: %8" PRId64 "\n",
486 mItemsSubmitted, mItemsFinalized);
487 result.append(buffer);
488 snprintf(buffer, SIZE,
489 "Records Discarded: %8" PRId64
490 " (by Count: %" PRId64 " by Expiration: %" PRId64 ")\n",
491 mItemsDiscarded, mItemsDiscardedCount, mItemsDiscardedExpire);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800492 result.append(buffer);
Ray Essick2e9c63b2017-03-29 15:16:44 -0700493 snprintf(buffer, SIZE,
494 "Summary Sets Discarded: %" PRId64 "\n", mSetsDiscarded);
495 result.append(buffer);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800496 if (ts_since != 0) {
497 snprintf(buffer, SIZE,
498 "Dumping Queue entries more recent than: %" PRId64 "\n",
499 (int64_t) ts_since);
500 result.append(buffer);
501 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700502}
503
504// dump summary info
505void MediaAnalyticsService::dumpSummaries(String8 &result, nsecs_t ts_since, const char *only) {
506 const size_t SIZE = 512;
507 char buffer[SIZE];
508 int slot = 0;
509
510 snprintf(buffer, SIZE, "\nSummarized Metrics:\n");
511 result.append(buffer);
512
Ray Essickf65f4212017-08-31 11:41:19 -0700513 if (only != NULL && *only == '\0') {
514 only = NULL;
515 }
516
Ray Essick2e9c63b2017-03-29 15:16:44 -0700517 // have each of the distillers dump records
518 if (mSummarizerSets != NULL) {
519 List<SummarizerSet *>::iterator itSet = mSummarizerSets->begin();
520 for (; itSet != mSummarizerSets->end(); itSet++) {
521 nsecs_t when = (*itSet)->getStarted();
522 if (when < ts_since) {
523 continue;
524 }
525 List<MetricsSummarizer *> *list = (*itSet)->getSummarizers();
526 List<MetricsSummarizer *>::iterator it = list->begin();
527 for (; it != list->end(); it++) {
528 if (only != NULL && strcmp(only, (*it)->getKey()) != 0) {
529 ALOGV("Told to omit '%s'", (*it)->getKey());
530 }
531 AString distilled = (*it)->dumpSummary(slot, only);
532 result.append(distilled.c_str());
533 }
534 }
535 }
536}
537
538// the recent, detailed queues
539void MediaAnalyticsService::dumpRecent(String8 &result, nsecs_t ts_since, const char * only) {
540 const size_t SIZE = 512;
541 char buffer[SIZE];
Ray Essickb5fac8e2016-12-12 11:33:56 -0800542
Ray Essickf65f4212017-08-31 11:41:19 -0700543 if (only != NULL && *only == '\0') {
544 only = NULL;
545 }
546
Ray Essickb5fac8e2016-12-12 11:33:56 -0800547 // show the recently recorded records
Ray Essickd38e1742017-01-23 15:17:06 -0800548 snprintf(buffer, sizeof(buffer), "\nFinalized Metrics (oldest first):\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800549 result.append(buffer);
Ray Essick2e9c63b2017-03-29 15:16:44 -0700550 result.append(this->dumpQueue(mFinalized, ts_since, only));
Ray Essickb5fac8e2016-12-12 11:33:56 -0800551
Ray Essickd38e1742017-01-23 15:17:06 -0800552 snprintf(buffer, sizeof(buffer), "\nIn-Progress Metrics (newest first):\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800553 result.append(buffer);
Ray Essick2e9c63b2017-03-29 15:16:44 -0700554 result.append(this->dumpQueue(mOpen, ts_since, only));
Ray Essickb5fac8e2016-12-12 11:33:56 -0800555
556 // show who is connected and injecting records?
557 // talk about # records fed to the 'readers'
558 // talk about # records we discarded, perhaps "discarded w/o reading" too
Ray Essick3938dc62016-11-01 08:56:56 -0700559}
Ray Essick3938dc62016-11-01 08:56:56 -0700560// caller has locked mLock...
Ray Essickb5fac8e2016-12-12 11:33:56 -0800561String8 MediaAnalyticsService::dumpQueue(List<MediaAnalyticsItem *> *theList) {
Ray Essick2e9c63b2017-03-29 15:16:44 -0700562 return dumpQueue(theList, (nsecs_t) 0, NULL);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800563}
564
Ray Essick2e9c63b2017-03-29 15:16:44 -0700565String8 MediaAnalyticsService::dumpQueue(List<MediaAnalyticsItem *> *theList, nsecs_t ts_since, const char * only) {
Ray Essick3938dc62016-11-01 08:56:56 -0700566 String8 result;
567 int slot = 0;
568
569 if (theList->empty()) {
570 result.append("empty\n");
571 } else {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800572 List<MediaAnalyticsItem *>::iterator it = theList->begin();
573 for (; it != theList->end(); it++) {
574 nsecs_t when = (*it)->getTimestamp();
575 if (when < ts_since) {
576 continue;
577 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700578 if (only != NULL &&
579 strcmp(only, (*it)->getKey().c_str()) != 0) {
580 ALOGV("Omit '%s', it's not '%s'", (*it)->getKey().c_str(), only);
581 continue;
582 }
Ray Essickf65f4212017-08-31 11:41:19 -0700583 AString entry = (*it)->toString(mDumpProto);
Ray Essick35ad27f2017-01-30 14:04:11 -0800584 result.appendFormat("%5d: %s\n", slot, entry.c_str());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800585 slot++;
Ray Essick3938dc62016-11-01 08:56:56 -0700586 }
587 }
588
589 return result;
590}
591
592//
593// Our Cheap in-core, non-persistent records management.
594// XXX: rewrite this to manage persistence, etc.
595
596// insert appropriately into queue
Ray Essickb5fac8e2016-12-12 11:33:56 -0800597void MediaAnalyticsService::saveItem(List<MediaAnalyticsItem *> *l, MediaAnalyticsItem * item, int front) {
Ray Essick3938dc62016-11-01 08:56:56 -0700598
599 Mutex::Autolock _l(mLock);
600
Ray Essick3938dc62016-11-01 08:56:56 -0700601 // adding at back of queue (fifo order)
602 if (front) {
603 l->push_front(item);
604 } else {
605 l->push_back(item);
606 }
607
Ray Essickf65f4212017-08-31 11:41:19 -0700608 // keep removing old records the front until we're in-bounds (count)
Ray Essick3938dc62016-11-01 08:56:56 -0700609 if (mMaxRecords > 0) {
610 while (l->size() > (size_t) mMaxRecords) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800611 MediaAnalyticsItem * oitem = *(l->begin());
Ray Essick3938dc62016-11-01 08:56:56 -0700612 l->erase(l->begin());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800613 delete oitem;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800614 mItemsDiscarded++;
Ray Essickf65f4212017-08-31 11:41:19 -0700615 mItemsDiscardedCount++;
616 }
617 }
618
619 // keep removing old records the front until we're in-bounds (count)
620 if (mMaxRecordAgeNs > 0) {
621 nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
622 while (l->size() > 0) {
623 MediaAnalyticsItem * oitem = *(l->begin());
624 nsecs_t when = oitem->getTimestamp();
625// DEBUGGING -- remove this ALOGD() call
626 if(0) ALOGD("@ now=%10" PRId64 " record when=%10" PRId64 "",
627 now, when);
628 // careful about timejumps too
629 if ((now > when) && (now-when) <= mMaxRecordAgeNs) {
630 // this (and the rest) are recent enough to keep
631 break;
632 }
633 l->erase(l->begin());
634 delete oitem;
635 mItemsDiscarded++;
636 mItemsDiscardedExpire++;
Ray Essick3938dc62016-11-01 08:56:56 -0700637 }
638 }
Ray Essick3938dc62016-11-01 08:56:56 -0700639}
640
641// are they alike enough that nitem can be folded into oitem?
Ray Essickb5fac8e2016-12-12 11:33:56 -0800642static bool compatibleItems(MediaAnalyticsItem * oitem, MediaAnalyticsItem * nitem) {
Ray Essick3938dc62016-11-01 08:56:56 -0700643
644 if (0) {
645 ALOGD("Compare: o %s n %s",
646 oitem->toString().c_str(), nitem->toString().c_str());
647 }
648
649 // general safety
650 if (nitem->getUid() != oitem->getUid()) {
651 return false;
652 }
653 if (nitem->getPid() != oitem->getPid()) {
654 return false;
655 }
656
657 // key -- needs to match
658 if (nitem->getKey() == oitem->getKey()) {
659 // still in the game.
660 } else {
661 return false;
662 }
663
664 // session id -- empty field in new is allowed
665 MediaAnalyticsItem::SessionID_t osession = oitem->getSessionID();
666 MediaAnalyticsItem::SessionID_t nsession = nitem->getSessionID();
667 if (nsession != osession) {
668 // incoming '0' matches value in osession
669 if (nsession != 0) {
670 return false;
671 }
672 }
673
674 return true;
675}
676
677// find the incomplete record that this will overlay
Ray Essickb5fac8e2016-12-12 11:33:56 -0800678MediaAnalyticsItem *MediaAnalyticsService::findItem(List<MediaAnalyticsItem*> *theList, MediaAnalyticsItem *nitem, bool removeit) {
Ray Essick3938dc62016-11-01 08:56:56 -0700679 if (nitem == NULL) {
680 return NULL;
681 }
682
Ray Essickb5fac8e2016-12-12 11:33:56 -0800683 MediaAnalyticsItem *item = NULL;
684
Ray Essick3938dc62016-11-01 08:56:56 -0700685 Mutex::Autolock _l(mLock);
686
Ray Essickb5fac8e2016-12-12 11:33:56 -0800687 for (List<MediaAnalyticsItem *>::iterator it = theList->begin();
Ray Essick3938dc62016-11-01 08:56:56 -0700688 it != theList->end(); it++) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800689 MediaAnalyticsItem *tmp = (*it);
Ray Essick3938dc62016-11-01 08:56:56 -0700690
691 if (!compatibleItems(tmp, nitem)) {
692 continue;
693 }
694
695 // we match! this is the one I want.
696 if (removeit) {
697 theList->erase(it);
698 }
699 item = tmp;
700 break;
701 }
702 return item;
703}
704
705
706// delete the indicated record
Ray Essickb5fac8e2016-12-12 11:33:56 -0800707void MediaAnalyticsService::deleteItem(List<MediaAnalyticsItem *> *l, MediaAnalyticsItem *item) {
Ray Essick3938dc62016-11-01 08:56:56 -0700708
709 Mutex::Autolock _l(mLock);
710
Ray Essickb5fac8e2016-12-12 11:33:56 -0800711 for (List<MediaAnalyticsItem *>::iterator it = l->begin();
Ray Essick3938dc62016-11-01 08:56:56 -0700712 it != l->end(); it++) {
713 if ((*it)->getSessionID() != item->getSessionID())
714 continue;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800715 delete *it;
Ray Essick3938dc62016-11-01 08:56:56 -0700716 l->erase(it);
717 break;
718 }
Ray Essick3938dc62016-11-01 08:56:56 -0700719}
720
Ray Essickd38e1742017-01-23 15:17:06 -0800721static AString allowedKeys[] =
722{
723 "codec",
724 "extractor"
725};
Ray Essick3938dc62016-11-01 08:56:56 -0700726
Ray Essickd38e1742017-01-23 15:17:06 -0800727static const int nAllowedKeys = sizeof(allowedKeys) / sizeof(allowedKeys[0]);
728
729// are the contents good
730bool MediaAnalyticsService::contentValid(MediaAnalyticsItem *item, bool isTrusted) {
731
732 // untrusted uids can only send us a limited set of keys
733 if (isTrusted == false) {
734 // restrict to a specific set of keys
735 AString key = item->getKey();
736
737 size_t i;
738 for(i = 0; i < nAllowedKeys; i++) {
739 if (key == allowedKeys[i]) {
740 break;
741 }
742 }
743 if (i == nAllowedKeys) {
744 ALOGD("Ignoring (key): %s", item->toString().c_str());
745 return false;
746 }
747 }
748
Ray Essick3938dc62016-11-01 08:56:56 -0700749 // internal consistency
750
751 return true;
752}
753
754// are we rate limited, normally false
Ray Essickb5fac8e2016-12-12 11:33:56 -0800755bool MediaAnalyticsService::rateLimited(MediaAnalyticsItem *) {
Ray Essick3938dc62016-11-01 08:56:56 -0700756
757 return false;
758}
759
Ray Essick2e9c63b2017-03-29 15:16:44 -0700760// insert into the appropriate summarizer.
761// we make our own copy to save/summarize
762void MediaAnalyticsService::summarize(MediaAnalyticsItem *item) {
763
764 ALOGV("MediaAnalyticsService::summarize()");
765
766 if (item == NULL) {
767 return;
768 }
769
770 nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
771 if (mCurrentSet == NULL
772 || (mCurrentSet->getStarted() + mNewSetInterval < now)) {
773 newSummarizerSet();
774 }
775
776 if (mCurrentSet == NULL) {
777 return;
778 }
779
780 List<MetricsSummarizer *> *summarizers = mCurrentSet->getSummarizers();
781 List<MetricsSummarizer *>::iterator it = summarizers->begin();
782 for (; it != summarizers->end(); it++) {
783 if ((*it)->isMine(*item)) {
784 break;
785 }
786 }
787 if (it == summarizers->end()) {
788 ALOGD("no handler for type %s", item->getKey().c_str());
789 return; // no handler
790 }
791
792 // invoke the summarizer. summarizer will make whatever copies
793 // it wants; the caller retains ownership of item.
794
795 (*it)->handleRecord(item);
796
797}
Ray Essick3938dc62016-11-01 08:56:56 -0700798
Ray Essickf65f4212017-08-31 11:41:19 -0700799// mapping uids to package names
800
801// give me the package name, perhaps going to find it
802AString MediaAnalyticsService::getPkgName(uid_t uid, bool addIfMissing) {
803 ssize_t i = mPkgMappings.indexOfKey(uid);
804 if (i >= 0) {
805 AString pkg = mPkgMappings.valueAt(i);
806 ALOGV("returning pkg '%s' for uid %d", pkg.c_str(), uid);
807 return pkg;
808 }
809
810 AString pkg;
811
812 if (addIfMissing == false) {
813 return pkg;
814 }
815
816 struct passwd *pw = getpwuid(uid);
817 if (pw) {
818 pkg = pw->pw_name;
819 } else {
820 pkg = "-";
821 }
822
823 // find the proper value
824
825 sp<IBinder> binder = NULL;
826 sp<IServiceManager> sm = defaultServiceManager();
827 if (sm == NULL) {
828 ALOGE("defaultServiceManager failed");
829 } else {
830 binder = sm->getService(String16("package_native"));
831 if (binder == NULL) {
832 ALOGE("getService package_native failed");
833 }
834 }
835
836 if (binder != NULL) {
837 sp<IPackageManagerNative> package_mgr = interface_cast<IPackageManagerNative>(binder);
838
839 std::vector<int> uids;
840 std::vector<std::string> names;
841
842 uids.push_back(uid);
843
844 binder::Status status = package_mgr->getNamesForUids(uids, &names);
845 if (!status.isOk()) {
846 ALOGE("package_native::getNamesForUids failed: %s",
847 status.exceptionMessage().c_str());
848 } else {
849 if (!names[0].empty()) {
850 pkg = names[0].c_str();
851 }
852 }
853 }
854
855 // XXX determine whether package was side-loaded or from playstore.
856 // for privacy, we only list apps loaded from playstore.
857
858 // Sanitize the package name for ":"
859 // as an example, we get "shared:android.uid.systemui"
860 // replace : with something benign (I'm going to use !)
861 if (!pkg.empty()) {
862 int n = pkg.size();
863 char *p = (char *) pkg.c_str();
864 for (int i = 0 ; i < n; i++) {
865 if (p[i] == ':') {
866 p[i] = '!';
867 }
868 }
869 }
870
871 // add it to the map, to save a subsequent lookup
872 if (!pkg.empty()) {
873 ALOGV("Adding uid %d pkg '%s'", uid, pkg.c_str());
874 mPkgMappings.add(uid, pkg);
875 }
876
877 return pkg;
878}
879
Ray Essick3938dc62016-11-01 08:56:56 -0700880} // namespace android