blob: 763b937aaac1cf23e41fc1bd4c7097ff95945679 [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);
Ray Essick721b7a02017-09-11 09:33:56 -0700225 // round nsecs to seconds
226 now = ((now + 500000000) / 1000000000) * 1000000000;
Ray Essick3938dc62016-11-01 08:56:56 -0700227 item->setTimestamp(now);
228 int pid = IPCThreadState::self()->getCallingPid();
Ray Essick3938dc62016-11-01 08:56:56 -0700229 int uid = IPCThreadState::self()->getCallingUid();
Ray Essickd38e1742017-01-23 15:17:06 -0800230
231 int uid_given = item->getUid();
232 int pid_given = item->getPid();
233
234 // although we do make exceptions for particular client uids
235 // that we know we trust.
236 //
237 bool isTrusted = false;
238
Ray Essickf65f4212017-08-31 11:41:19 -0700239 ALOGV("caller has uid=%d, embedded uid=%d", uid, uid_given);
240
Ray Essickd38e1742017-01-23 15:17:06 -0800241 switch (uid) {
242 case AID_MEDIA:
243 case AID_MEDIA_CODEC:
244 case AID_MEDIA_EX:
245 case AID_MEDIA_DRM:
246 // trusted source, only override default values
Ray Essickf65f4212017-08-31 11:41:19 -0700247 isTrusted = true;
Ray Essickd38e1742017-01-23 15:17:06 -0800248 if (uid_given == (-1)) {
249 item->setUid(uid);
250 }
251 if (pid_given == (-1)) {
252 item->setPid(pid);
253 }
254 break;
255 default:
256 isTrusted = false;
257 item->setPid(pid);
258 item->setUid(uid);
259 break;
260 }
261
Adam Stone21c72122017-09-05 19:02:06 -0700262 // Overwrite package name and version if the caller was untrusted.
263 if (!isTrusted) {
264 item->setPkgName(getPkgName(item->getUid(), true));
265 item->setPkgVersionCode(0);
266 } else if (item->getPkgName().empty()) {
267 // Only overwrite the package name if it was empty. Trust whatever
268 // version code was provided by the trusted caller.
269 item->setPkgName(getPkgName(uid, true));
270 }
271
272 ALOGV("given uid %d; sanitized uid: %d sanitized pkg: %s "
273 "sanitized pkg version: %d",
274 uid_given, item->getUid(),
275 item->getPkgName().c_str(),
276 item->getPkgVersionCode());
Ray Essick3938dc62016-11-01 08:56:56 -0700277
278 mItemsSubmitted++;
279
280 // validate the record; we discard if we don't like it
Ray Essickd38e1742017-01-23 15:17:06 -0800281 if (contentValid(item, isTrusted) == false) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800282 delete item;
Ray Essick3938dc62016-11-01 08:56:56 -0700283 return MediaAnalyticsItem::SessionIDInvalid;
284 }
285
286
287 // if we have a sesisonid in the new record, look to make
288 // sure it doesn't appear in the finalized list.
289 // XXX: this is for security / DOS prevention.
290 // may also require that we persist the unique sessionIDs
291 // across boots [instead of within a single boot]
292
293
294 // match this new record up against records in the open
295 // list...
296 // if there's a match, merge them together
297 // deal with moving the old / merged record into the finalized que
298
299 bool finalizing = item->getFinalized();
300
301 // if finalizing, we'll remove it
Ray Essickb5fac8e2016-12-12 11:33:56 -0800302 MediaAnalyticsItem *oitem = findItem(mOpen, item, finalizing | forcenew);
Ray Essick3938dc62016-11-01 08:56:56 -0700303 if (oitem != NULL) {
304 if (forcenew) {
305 // old one gets finalized, then we insert the new one
306 // so we'll have 2 records at the end of this.
307 // but don't finalize an empty record
Ray Essickb5fac8e2016-12-12 11:33:56 -0800308 if (oitem->count() == 0) {
309 // we're responsible for disposing of the dead record
310 delete oitem;
311 oitem = NULL;
312 } else {
Ray Essick3938dc62016-11-01 08:56:56 -0700313 oitem->setFinalized(true);
Ray Essick2e9c63b2017-03-29 15:16:44 -0700314 summarize(oitem);
Ray Essick3938dc62016-11-01 08:56:56 -0700315 saveItem(mFinalized, oitem, 0);
316 }
317 // new record could itself be marked finalized...
318 if (finalizing) {
Ray Essick2e9c63b2017-03-29 15:16:44 -0700319 summarize(item);
Ray Essick3938dc62016-11-01 08:56:56 -0700320 saveItem(mFinalized, item, 0);
321 mItemsFinalized++;
322 } else {
323 saveItem(mOpen, item, 1);
324 }
325 id = item->getSessionID();
326 } else {
327 // combine the records, send it to finalized if appropriate
328 oitem->merge(item);
329 if (finalizing) {
Ray Essick2e9c63b2017-03-29 15:16:44 -0700330 summarize(oitem);
Ray Essick3938dc62016-11-01 08:56:56 -0700331 saveItem(mFinalized, oitem, 0);
332 mItemsFinalized++;
333 }
334 id = oitem->getSessionID();
Ray Essickb5fac8e2016-12-12 11:33:56 -0800335
336 // we're responsible for disposing of the dead record
337 delete item;
338 item = NULL;
Ray Essick3938dc62016-11-01 08:56:56 -0700339 }
340 } else {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800341 // nothing to merge, save the new record
342 id = item->getSessionID();
343 if (finalizing) {
344 if (item->count() == 0) {
345 // drop empty records
346 delete item;
347 item = NULL;
Ray Essick3938dc62016-11-01 08:56:56 -0700348 } else {
Ray Essick2e9c63b2017-03-29 15:16:44 -0700349 summarize(item);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800350 saveItem(mFinalized, item, 0);
351 mItemsFinalized++;
Ray Essick3938dc62016-11-01 08:56:56 -0700352 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800353 } else {
354 saveItem(mOpen, item, 1);
355 }
Ray Essick3938dc62016-11-01 08:56:56 -0700356 }
Ray Essick3938dc62016-11-01 08:56:56 -0700357 return id;
358}
359
Ray Essickf65f4212017-08-31 11:41:19 -0700360
Ray Essickb5fac8e2016-12-12 11:33:56 -0800361status_t MediaAnalyticsService::dump(int fd, const Vector<String16>& args)
Ray Essick3938dc62016-11-01 08:56:56 -0700362{
Ray Essickb5fac8e2016-12-12 11:33:56 -0800363 const size_t SIZE = 512;
Ray Essick3938dc62016-11-01 08:56:56 -0700364 char buffer[SIZE];
365 String8 result;
366
367 if (checkCallingPermission(String16("android.permission.DUMP")) == false) {
368 snprintf(buffer, SIZE, "Permission Denial: "
369 "can't dump MediaAnalyticsService from pid=%d, uid=%d\n",
370 IPCThreadState::self()->getCallingPid(),
371 IPCThreadState::self()->getCallingUid());
372 result.append(buffer);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800373 write(fd, result.string(), result.size());
374 return NO_ERROR;
Ray Essick3938dc62016-11-01 08:56:56 -0700375 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800376
377 // crack any parameters
Ray Essick2e9c63b2017-03-29 15:16:44 -0700378 String16 summaryOption("-summary");
Ray Essickf65f4212017-08-31 11:41:19 -0700379 bool summary = false;
380 String16 protoOption("-proto");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800381 String16 clearOption("-clear");
Ray Essickf65f4212017-08-31 11:41:19 -0700382 bool clear = false;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800383 String16 sinceOption("-since");
Ray Essickf65f4212017-08-31 11:41:19 -0700384 nsecs_t ts_since = 0;
Ray Essick35ad27f2017-01-30 14:04:11 -0800385 String16 helpOption("-help");
Ray Essick2e9c63b2017-03-29 15:16:44 -0700386 String16 onlyOption("-only");
Ray Essickf65f4212017-08-31 11:41:19 -0700387 AString only;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800388 int n = args.size();
Ray Essickf65f4212017-08-31 11:41:19 -0700389
Ray Essickb5fac8e2016-12-12 11:33:56 -0800390 for (int i = 0; i < n; i++) {
391 String8 myarg(args[i]);
392 if (args[i] == clearOption) {
393 clear = true;
Ray Essick2e9c63b2017-03-29 15:16:44 -0700394 } else if (args[i] == summaryOption) {
395 summary = true;
Ray Essickf65f4212017-08-31 11:41:19 -0700396 } else if (args[i] == protoOption) {
397 i++;
398 if (i < n) {
399 String8 value(args[i]);
400 int proto = MediaAnalyticsItem::PROTO_V0; // default to original
401 char *endp;
402 const char *p = value.string();
403 proto = strtol(p, &endp, 10);
404 if (endp != p || *endp == '\0') {
405 if (proto < MediaAnalyticsItem::PROTO_FIRST) {
406 proto = MediaAnalyticsItem::PROTO_FIRST;
407 } else if (proto > MediaAnalyticsItem::PROTO_LAST) {
408 proto = MediaAnalyticsItem::PROTO_LAST;
409 }
410 mDumpProto = proto;
411 }
412 }
Ray Essickb5fac8e2016-12-12 11:33:56 -0800413 } else if (args[i] == sinceOption) {
414 i++;
415 if (i < n) {
416 String8 value(args[i]);
417 char *endp;
418 const char *p = value.string();
419 ts_since = strtoll(p, &endp, 10);
420 if (endp == p || *endp != '\0') {
421 ts_since = 0;
422 }
423 } else {
424 ts_since = 0;
425 }
Ray Essick35ad27f2017-01-30 14:04:11 -0800426 // command line is milliseconds; internal units are nano-seconds
427 ts_since *= 1000*1000;
Ray Essick2e9c63b2017-03-29 15:16:44 -0700428 } else if (args[i] == onlyOption) {
429 i++;
430 if (i < n) {
431 String8 value(args[i]);
Ray Essickf65f4212017-08-31 11:41:19 -0700432 only = value.string();
Ray Essick2e9c63b2017-03-29 15:16:44 -0700433 }
Ray Essick35ad27f2017-01-30 14:04:11 -0800434 } else if (args[i] == helpOption) {
435 result.append("Recognized parameters:\n");
436 result.append("-help this help message\n");
Ray Essickf65f4212017-08-31 11:41:19 -0700437 result.append("-proto X dump using protocol X (defaults to 1)");
Ray Essick2e9c63b2017-03-29 15:16:44 -0700438 result.append("-summary show summary info\n");
Ray Essick35ad27f2017-01-30 14:04:11 -0800439 result.append("-clear clears out saved records\n");
Ray Essick2e9c63b2017-03-29 15:16:44 -0700440 result.append("-only X process records for component X\n");
441 result.append("-since X include records since X\n");
442 result.append(" (X is milliseconds since the UNIX epoch)\n");
Ray Essick35ad27f2017-01-30 14:04:11 -0800443 write(fd, result.string(), result.size());
444 return NO_ERROR;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800445 }
446 }
447
448 Mutex::Autolock _l(mLock);
449
Ray Essick2e9c63b2017-03-29 15:16:44 -0700450 // we ALWAYS dump this piece
451 snprintf(buffer, SIZE, "Dump of the %s process:\n", kServiceName);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800452 result.append(buffer);
453
Ray Essick2e9c63b2017-03-29 15:16:44 -0700454 dumpHeaders(result, ts_since);
455
Ray Essickf65f4212017-08-31 11:41:19 -0700456 // want exactly 1, to avoid confusing folks that parse the output
Ray Essick2e9c63b2017-03-29 15:16:44 -0700457 if (summary) {
Ray Essickf65f4212017-08-31 11:41:19 -0700458 dumpSummaries(result, ts_since, only.c_str());
Ray Essick2e9c63b2017-03-29 15:16:44 -0700459 } else {
Ray Essickf65f4212017-08-31 11:41:19 -0700460 dumpRecent(result, ts_since, only.c_str());
Ray Essick2e9c63b2017-03-29 15:16:44 -0700461 }
462
463
464 if (clear) {
465 // remove everything from the finalized queue
466 while (mFinalized->size() > 0) {
467 MediaAnalyticsItem * oitem = *(mFinalized->begin());
468 mFinalized->erase(mFinalized->begin());
469 delete oitem;
470 mItemsDiscarded++;
471 }
472
473 // shall we clear the summary data too?
474
475 }
476
477 write(fd, result.string(), result.size());
478 return NO_ERROR;
479}
480
481// dump headers
482void MediaAnalyticsService::dumpHeaders(String8 &result, nsecs_t ts_since) {
483 const size_t SIZE = 512;
484 char buffer[SIZE];
485
Ray Essickf65f4212017-08-31 11:41:19 -0700486 snprintf(buffer, SIZE, "Protocol Version: %d\n", mDumpProto);
487 result.append(buffer);
488
Ray Essickb5fac8e2016-12-12 11:33:56 -0800489 int enabled = MediaAnalyticsItem::isEnabled();
490 if (enabled) {
Ray Essickd38e1742017-01-23 15:17:06 -0800491 snprintf(buffer, SIZE, "Metrics gathering: enabled\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800492 } else {
Ray Essickd38e1742017-01-23 15:17:06 -0800493 snprintf(buffer, SIZE, "Metrics gathering: DISABLED via property\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800494 }
495 result.append(buffer);
496
497 snprintf(buffer, SIZE,
Ray Essickf65f4212017-08-31 11:41:19 -0700498 "Since Boot: Submissions: %8" PRId64
499 " Finalizations: %8" PRId64 "\n",
500 mItemsSubmitted, mItemsFinalized);
501 result.append(buffer);
502 snprintf(buffer, SIZE,
503 "Records Discarded: %8" PRId64
504 " (by Count: %" PRId64 " by Expiration: %" PRId64 ")\n",
505 mItemsDiscarded, mItemsDiscardedCount, mItemsDiscardedExpire);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800506 result.append(buffer);
Ray Essick2e9c63b2017-03-29 15:16:44 -0700507 snprintf(buffer, SIZE,
508 "Summary Sets Discarded: %" PRId64 "\n", mSetsDiscarded);
509 result.append(buffer);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800510 if (ts_since != 0) {
511 snprintf(buffer, SIZE,
512 "Dumping Queue entries more recent than: %" PRId64 "\n",
513 (int64_t) ts_since);
514 result.append(buffer);
515 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700516}
517
518// dump summary info
519void MediaAnalyticsService::dumpSummaries(String8 &result, nsecs_t ts_since, const char *only) {
520 const size_t SIZE = 512;
521 char buffer[SIZE];
522 int slot = 0;
523
524 snprintf(buffer, SIZE, "\nSummarized Metrics:\n");
525 result.append(buffer);
526
Ray Essickf65f4212017-08-31 11:41:19 -0700527 if (only != NULL && *only == '\0') {
528 only = NULL;
529 }
530
Ray Essick2e9c63b2017-03-29 15:16:44 -0700531 // have each of the distillers dump records
532 if (mSummarizerSets != NULL) {
533 List<SummarizerSet *>::iterator itSet = mSummarizerSets->begin();
534 for (; itSet != mSummarizerSets->end(); itSet++) {
535 nsecs_t when = (*itSet)->getStarted();
536 if (when < ts_since) {
537 continue;
538 }
539 List<MetricsSummarizer *> *list = (*itSet)->getSummarizers();
540 List<MetricsSummarizer *>::iterator it = list->begin();
541 for (; it != list->end(); it++) {
542 if (only != NULL && strcmp(only, (*it)->getKey()) != 0) {
543 ALOGV("Told to omit '%s'", (*it)->getKey());
544 }
545 AString distilled = (*it)->dumpSummary(slot, only);
546 result.append(distilled.c_str());
547 }
548 }
549 }
550}
551
552// the recent, detailed queues
553void MediaAnalyticsService::dumpRecent(String8 &result, nsecs_t ts_since, const char * only) {
554 const size_t SIZE = 512;
555 char buffer[SIZE];
Ray Essickb5fac8e2016-12-12 11:33:56 -0800556
Ray Essickf65f4212017-08-31 11:41:19 -0700557 if (only != NULL && *only == '\0') {
558 only = NULL;
559 }
560
Ray Essickb5fac8e2016-12-12 11:33:56 -0800561 // show the recently recorded records
Ray Essickd38e1742017-01-23 15:17:06 -0800562 snprintf(buffer, sizeof(buffer), "\nFinalized Metrics (oldest first):\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800563 result.append(buffer);
Ray Essick2e9c63b2017-03-29 15:16:44 -0700564 result.append(this->dumpQueue(mFinalized, ts_since, only));
Ray Essickb5fac8e2016-12-12 11:33:56 -0800565
Ray Essickd38e1742017-01-23 15:17:06 -0800566 snprintf(buffer, sizeof(buffer), "\nIn-Progress Metrics (newest first):\n");
Ray Essickb5fac8e2016-12-12 11:33:56 -0800567 result.append(buffer);
Ray Essick2e9c63b2017-03-29 15:16:44 -0700568 result.append(this->dumpQueue(mOpen, ts_since, only));
Ray Essickb5fac8e2016-12-12 11:33:56 -0800569
570 // show who is connected and injecting records?
571 // talk about # records fed to the 'readers'
572 // talk about # records we discarded, perhaps "discarded w/o reading" too
Ray Essick3938dc62016-11-01 08:56:56 -0700573}
Ray Essick3938dc62016-11-01 08:56:56 -0700574// caller has locked mLock...
Ray Essickb5fac8e2016-12-12 11:33:56 -0800575String8 MediaAnalyticsService::dumpQueue(List<MediaAnalyticsItem *> *theList) {
Ray Essick2e9c63b2017-03-29 15:16:44 -0700576 return dumpQueue(theList, (nsecs_t) 0, NULL);
Ray Essickb5fac8e2016-12-12 11:33:56 -0800577}
578
Ray Essick2e9c63b2017-03-29 15:16:44 -0700579String8 MediaAnalyticsService::dumpQueue(List<MediaAnalyticsItem *> *theList, nsecs_t ts_since, const char * only) {
Ray Essick3938dc62016-11-01 08:56:56 -0700580 String8 result;
581 int slot = 0;
582
583 if (theList->empty()) {
584 result.append("empty\n");
585 } else {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800586 List<MediaAnalyticsItem *>::iterator it = theList->begin();
587 for (; it != theList->end(); it++) {
588 nsecs_t when = (*it)->getTimestamp();
589 if (when < ts_since) {
590 continue;
591 }
Ray Essick2e9c63b2017-03-29 15:16:44 -0700592 if (only != NULL &&
593 strcmp(only, (*it)->getKey().c_str()) != 0) {
594 ALOGV("Omit '%s', it's not '%s'", (*it)->getKey().c_str(), only);
595 continue;
596 }
Ray Essickf65f4212017-08-31 11:41:19 -0700597 AString entry = (*it)->toString(mDumpProto);
Ray Essick35ad27f2017-01-30 14:04:11 -0800598 result.appendFormat("%5d: %s\n", slot, entry.c_str());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800599 slot++;
Ray Essick3938dc62016-11-01 08:56:56 -0700600 }
601 }
602
603 return result;
604}
605
606//
607// Our Cheap in-core, non-persistent records management.
608// XXX: rewrite this to manage persistence, etc.
609
610// insert appropriately into queue
Ray Essickb5fac8e2016-12-12 11:33:56 -0800611void MediaAnalyticsService::saveItem(List<MediaAnalyticsItem *> *l, MediaAnalyticsItem * item, int front) {
Ray Essick3938dc62016-11-01 08:56:56 -0700612
613 Mutex::Autolock _l(mLock);
614
Ray Essick3938dc62016-11-01 08:56:56 -0700615 // adding at back of queue (fifo order)
616 if (front) {
617 l->push_front(item);
618 } else {
619 l->push_back(item);
620 }
621
Ray Essickf65f4212017-08-31 11:41:19 -0700622 // keep removing old records the front until we're in-bounds (count)
Ray Essick3938dc62016-11-01 08:56:56 -0700623 if (mMaxRecords > 0) {
624 while (l->size() > (size_t) mMaxRecords) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800625 MediaAnalyticsItem * oitem = *(l->begin());
Ray Essick3938dc62016-11-01 08:56:56 -0700626 l->erase(l->begin());
Ray Essickb5fac8e2016-12-12 11:33:56 -0800627 delete oitem;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800628 mItemsDiscarded++;
Ray Essickf65f4212017-08-31 11:41:19 -0700629 mItemsDiscardedCount++;
630 }
631 }
632
633 // keep removing old records the front until we're in-bounds (count)
634 if (mMaxRecordAgeNs > 0) {
635 nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
636 while (l->size() > 0) {
637 MediaAnalyticsItem * oitem = *(l->begin());
638 nsecs_t when = oitem->getTimestamp();
Ray Essickf65f4212017-08-31 11:41:19 -0700639 // careful about timejumps too
640 if ((now > when) && (now-when) <= mMaxRecordAgeNs) {
641 // this (and the rest) are recent enough to keep
642 break;
643 }
644 l->erase(l->begin());
645 delete oitem;
646 mItemsDiscarded++;
647 mItemsDiscardedExpire++;
Ray Essick3938dc62016-11-01 08:56:56 -0700648 }
649 }
Ray Essick3938dc62016-11-01 08:56:56 -0700650}
651
652// are they alike enough that nitem can be folded into oitem?
Ray Essickb5fac8e2016-12-12 11:33:56 -0800653static bool compatibleItems(MediaAnalyticsItem * oitem, MediaAnalyticsItem * nitem) {
Ray Essick3938dc62016-11-01 08:56:56 -0700654
Ray Essick3938dc62016-11-01 08:56:56 -0700655 // general safety
656 if (nitem->getUid() != oitem->getUid()) {
657 return false;
658 }
659 if (nitem->getPid() != oitem->getPid()) {
660 return false;
661 }
662
663 // key -- needs to match
664 if (nitem->getKey() == oitem->getKey()) {
665 // still in the game.
666 } else {
667 return false;
668 }
669
670 // session id -- empty field in new is allowed
671 MediaAnalyticsItem::SessionID_t osession = oitem->getSessionID();
672 MediaAnalyticsItem::SessionID_t nsession = nitem->getSessionID();
673 if (nsession != osession) {
674 // incoming '0' matches value in osession
675 if (nsession != 0) {
676 return false;
677 }
678 }
679
680 return true;
681}
682
683// find the incomplete record that this will overlay
Ray Essickb5fac8e2016-12-12 11:33:56 -0800684MediaAnalyticsItem *MediaAnalyticsService::findItem(List<MediaAnalyticsItem*> *theList, MediaAnalyticsItem *nitem, bool removeit) {
Ray Essick3938dc62016-11-01 08:56:56 -0700685 if (nitem == NULL) {
686 return NULL;
687 }
688
Ray Essickb5fac8e2016-12-12 11:33:56 -0800689 MediaAnalyticsItem *item = NULL;
690
Ray Essick3938dc62016-11-01 08:56:56 -0700691 Mutex::Autolock _l(mLock);
692
Ray Essickb5fac8e2016-12-12 11:33:56 -0800693 for (List<MediaAnalyticsItem *>::iterator it = theList->begin();
Ray Essick3938dc62016-11-01 08:56:56 -0700694 it != theList->end(); it++) {
Ray Essickb5fac8e2016-12-12 11:33:56 -0800695 MediaAnalyticsItem *tmp = (*it);
Ray Essick3938dc62016-11-01 08:56:56 -0700696
697 if (!compatibleItems(tmp, nitem)) {
698 continue;
699 }
700
701 // we match! this is the one I want.
702 if (removeit) {
703 theList->erase(it);
704 }
705 item = tmp;
706 break;
707 }
708 return item;
709}
710
711
712// delete the indicated record
Ray Essickb5fac8e2016-12-12 11:33:56 -0800713void MediaAnalyticsService::deleteItem(List<MediaAnalyticsItem *> *l, MediaAnalyticsItem *item) {
Ray Essick3938dc62016-11-01 08:56:56 -0700714
715 Mutex::Autolock _l(mLock);
716
Ray Essickb5fac8e2016-12-12 11:33:56 -0800717 for (List<MediaAnalyticsItem *>::iterator it = l->begin();
Ray Essick3938dc62016-11-01 08:56:56 -0700718 it != l->end(); it++) {
719 if ((*it)->getSessionID() != item->getSessionID())
720 continue;
Ray Essickb5fac8e2016-12-12 11:33:56 -0800721 delete *it;
Ray Essick3938dc62016-11-01 08:56:56 -0700722 l->erase(it);
723 break;
724 }
Ray Essick3938dc62016-11-01 08:56:56 -0700725}
726
Ray Essickd38e1742017-01-23 15:17:06 -0800727static AString allowedKeys[] =
728{
729 "codec",
730 "extractor"
731};
Ray Essick3938dc62016-11-01 08:56:56 -0700732
Ray Essickd38e1742017-01-23 15:17:06 -0800733static const int nAllowedKeys = sizeof(allowedKeys) / sizeof(allowedKeys[0]);
734
735// are the contents good
736bool MediaAnalyticsService::contentValid(MediaAnalyticsItem *item, bool isTrusted) {
737
738 // untrusted uids can only send us a limited set of keys
739 if (isTrusted == false) {
740 // restrict to a specific set of keys
741 AString key = item->getKey();
742
743 size_t i;
744 for(i = 0; i < nAllowedKeys; i++) {
745 if (key == allowedKeys[i]) {
746 break;
747 }
748 }
749 if (i == nAllowedKeys) {
750 ALOGD("Ignoring (key): %s", item->toString().c_str());
751 return false;
752 }
753 }
754
Ray Essick3938dc62016-11-01 08:56:56 -0700755 // internal consistency
756
757 return true;
758}
759
760// are we rate limited, normally false
Ray Essickb5fac8e2016-12-12 11:33:56 -0800761bool MediaAnalyticsService::rateLimited(MediaAnalyticsItem *) {
Ray Essick3938dc62016-11-01 08:56:56 -0700762
763 return false;
764}
765
Ray Essick2e9c63b2017-03-29 15:16:44 -0700766// insert into the appropriate summarizer.
767// we make our own copy to save/summarize
768void MediaAnalyticsService::summarize(MediaAnalyticsItem *item) {
769
770 ALOGV("MediaAnalyticsService::summarize()");
771
772 if (item == NULL) {
773 return;
774 }
775
776 nsecs_t now = systemTime(SYSTEM_TIME_REALTIME);
777 if (mCurrentSet == NULL
778 || (mCurrentSet->getStarted() + mNewSetInterval < now)) {
779 newSummarizerSet();
780 }
781
782 if (mCurrentSet == NULL) {
783 return;
784 }
785
786 List<MetricsSummarizer *> *summarizers = mCurrentSet->getSummarizers();
787 List<MetricsSummarizer *>::iterator it = summarizers->begin();
788 for (; it != summarizers->end(); it++) {
789 if ((*it)->isMine(*item)) {
790 break;
791 }
792 }
793 if (it == summarizers->end()) {
794 ALOGD("no handler for type %s", item->getKey().c_str());
795 return; // no handler
796 }
797
798 // invoke the summarizer. summarizer will make whatever copies
799 // it wants; the caller retains ownership of item.
800
801 (*it)->handleRecord(item);
802
803}
Ray Essick3938dc62016-11-01 08:56:56 -0700804
Ray Essickf65f4212017-08-31 11:41:19 -0700805// mapping uids to package names
806
807// give me the package name, perhaps going to find it
808AString MediaAnalyticsService::getPkgName(uid_t uid, bool addIfMissing) {
809 ssize_t i = mPkgMappings.indexOfKey(uid);
810 if (i >= 0) {
811 AString pkg = mPkgMappings.valueAt(i);
812 ALOGV("returning pkg '%s' for uid %d", pkg.c_str(), uid);
813 return pkg;
814 }
815
816 AString pkg;
817
818 if (addIfMissing == false) {
819 return pkg;
820 }
821
822 struct passwd *pw = getpwuid(uid);
823 if (pw) {
824 pkg = pw->pw_name;
825 } else {
826 pkg = "-";
827 }
828
829 // find the proper value
830
831 sp<IBinder> binder = NULL;
832 sp<IServiceManager> sm = defaultServiceManager();
833 if (sm == NULL) {
834 ALOGE("defaultServiceManager failed");
835 } else {
836 binder = sm->getService(String16("package_native"));
837 if (binder == NULL) {
838 ALOGE("getService package_native failed");
839 }
840 }
841
842 if (binder != NULL) {
843 sp<IPackageManagerNative> package_mgr = interface_cast<IPackageManagerNative>(binder);
844
845 std::vector<int> uids;
846 std::vector<std::string> names;
847
848 uids.push_back(uid);
849
850 binder::Status status = package_mgr->getNamesForUids(uids, &names);
851 if (!status.isOk()) {
852 ALOGE("package_native::getNamesForUids failed: %s",
853 status.exceptionMessage().c_str());
854 } else {
855 if (!names[0].empty()) {
856 pkg = names[0].c_str();
857 }
858 }
859 }
860
861 // XXX determine whether package was side-loaded or from playstore.
862 // for privacy, we only list apps loaded from playstore.
863
864 // Sanitize the package name for ":"
865 // as an example, we get "shared:android.uid.systemui"
866 // replace : with something benign (I'm going to use !)
867 if (!pkg.empty()) {
868 int n = pkg.size();
869 char *p = (char *) pkg.c_str();
870 for (int i = 0 ; i < n; i++) {
871 if (p[i] == ':') {
872 p[i] = '!';
873 }
874 }
875 }
876
877 // add it to the map, to save a subsequent lookup
878 if (!pkg.empty()) {
879 ALOGV("Adding uid %d pkg '%s'", uid, pkg.c_str());
880 mPkgMappings.add(uid, pkg);
881 }
882
883 return pkg;
884}
885
Ray Essick3938dc62016-11-01 08:56:56 -0700886} // namespace android