blob: 7a127e07c55de737f12ebac715939416fcbbf2d2 [file] [log] [blame]
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001/*
yro0feae942017-11-15 14:38:48 -08002 * Copyright (C) 2017 The Android Open Source Project
Joe Onorato5dcbc6c2017-08-29 15:13:58 -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
Bookatzb487b552017-09-18 11:26:01 -070017#define DEBUG true
Joe Onorato9fc9edf2017-10-15 20:08:52 -070018#include "Log.h"
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070019
20#include "StatsService.h"
Yao Chen8d9989b2017-11-18 18:54:50 -080021#include "android-base/stringprintf.h"
David Chenadaf8b32017-11-03 15:42:08 -070022#include "config/ConfigKey.h"
23#include "config/ConfigManager.h"
Yao Chen8d9989b2017-11-18 18:54:50 -080024#include "guardrail/MemoryLeakTrackUtil.h"
Yao Chenb3561512017-11-21 18:07:17 -080025#include "guardrail/StatsdStats.h"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070026#include "storage/DropboxReader.h"
yro947fbce2017-11-15 22:50:23 -080027#include "storage/StorageManager.h"
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070028
David Chen0656b7a2017-09-13 15:53:39 -070029#include <android-base/file.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070030#include <binder/IPCThreadState.h>
31#include <binder/IServiceManager.h>
yro87d983c2017-11-14 21:31:43 -080032#include <dirent.h>
David Chen0656b7a2017-09-13 15:53:39 -070033#include <frameworks/base/cmds/statsd/src/statsd_config.pb.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070034#include <private/android_filesystem_config.h>
35#include <utils/Looper.h>
Joe Onorato2cbc2cc2017-08-30 17:03:23 -070036#include <utils/String16.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070037#include <stdio.h>
Yao Chen482d2722017-09-12 13:25:43 -070038#include <stdlib.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070039#include <sys/system_properties.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070040#include <unistd.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070041
42using namespace android;
43
Bookatz906a35c2017-09-20 15:26:44 -070044namespace android {
45namespace os {
46namespace statsd {
47
David Chenadaf8b32017-11-03 15:42:08 -070048constexpr const char* kPermissionDump = "android.permission.DUMP";
yro87d983c2017-11-14 21:31:43 -080049#define STATS_SERVICE_DIR "/data/system/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070050
Joe Onorato9fc9edf2017-10-15 20:08:52 -070051// ======================================================================
52/**
53 * Watches for the death of the stats companion (system process).
54 */
55class CompanionDeathRecipient : public IBinder::DeathRecipient {
56public:
57 CompanionDeathRecipient(const sp<AnomalyMonitor>& anomalyMonitor);
58 virtual void binderDied(const wp<IBinder>& who);
59
60private:
61 const sp<AnomalyMonitor> mAnomalyMonitor;
62};
63
64CompanionDeathRecipient::CompanionDeathRecipient(const sp<AnomalyMonitor>& anomalyMonitor)
65 : mAnomalyMonitor(anomalyMonitor) {
66}
67
68void CompanionDeathRecipient::binderDied(const wp<IBinder>& who) {
69 ALOGW("statscompanion service died");
70 mAnomalyMonitor->setStatsCompanionService(nullptr);
71}
72
73// ======================================================================
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070074StatsService::StatsService(const sp<Looper>& handlerLooper)
David Chen1481fe12017-10-16 13:16:34 -070075 : mAnomalyMonitor(new AnomalyMonitor(2)) // TODO: Put this comment somewhere better
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070076{
Joe Onorato9fc9edf2017-10-15 20:08:52 -070077 mUidMap = new UidMap();
78 mConfigManager = new ConfigManager();
Yangster-mace2cd6d52017-11-09 20:38:30 -080079 mProcessor = new StatsLogProcessor(mUidMap, mAnomalyMonitor, [this](const ConfigKey& key) {
yro947fbce2017-11-15 22:50:23 -080080 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen1d7b0cd2017-11-15 14:20:04 -080081 auto receiver = mConfigManager->GetConfigReceiver(key);
82 if (sc == nullptr) {
83 ALOGD("Could not find StatsCompanionService");
84 } else if (receiver.first.size() == 0) {
85 ALOGD("Statscompanion could not find a broadcast receiver for %s",
86 key.ToString().c_str());
87 } else {
88 sc->sendBroadcast(String16(receiver.first.c_str()),
89 String16(receiver.second.c_str()));
90 }
yro31eb67b2017-10-24 13:33:21 -070091 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -070092
93 mConfigManager->AddListener(mProcessor);
94
95 init_system_properties();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070096}
97
Yao Chenef99c4f2017-09-22 16:26:54 -070098StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070099}
100
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700101void StatsService::init_system_properties() {
102 mEngBuild = false;
103 const prop_info* buildType = __system_property_find("ro.build.type");
104 if (buildType != NULL) {
105 __system_property_read_callback(buildType, init_build_type_callback, this);
106 }
David Chen0656b7a2017-09-13 15:53:39 -0700107}
108
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700109void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
110 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700111 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700112 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
113 }
114}
115
116/**
117 * Implement our own because the default binder implementation isn't
118 * properly handling SHELL_COMMAND_TRANSACTION.
119 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700120status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
121 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700122 status_t err;
123
124 switch (code) {
125 case SHELL_COMMAND_TRANSACTION: {
126 int in = data.readFileDescriptor();
127 int out = data.readFileDescriptor();
128 int err = data.readFileDescriptor();
129 int argc = data.readInt32();
130 Vector<String8> args;
131 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
132 args.add(String8(data.readString16()));
133 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700134 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
135 sp<IResultReceiver> resultReceiver =
136 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700137
138 FILE* fin = fdopen(in, "r");
139 FILE* fout = fdopen(out, "w");
140 FILE* ferr = fdopen(err, "w");
141
142 if (fin == NULL || fout == NULL || ferr == NULL) {
143 resultReceiver->send(NO_MEMORY);
144 } else {
145 err = command(fin, fout, ferr, args);
146 resultReceiver->send(err);
147 }
148
149 if (fin != NULL) {
150 fflush(fin);
151 fclose(fin);
152 }
153 if (fout != NULL) {
154 fflush(fout);
155 fclose(fout);
156 }
157 if (fout != NULL) {
158 fflush(ferr);
159 fclose(ferr);
160 }
161
162 return NO_ERROR;
163 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700164 default: { return BnStatsManager::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700165 }
166}
167
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700168/**
169 * Write debugging data about statsd.
170 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700171status_t StatsService::dump(int fd, const Vector<String16>& args) {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700172 FILE* out = fdopen(fd, "w");
173 if (out == NULL) {
174 return NO_MEMORY; // the fd is already open
175 }
176
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700177 // TODO: Proto format for incident reports
178 dump_impl(out);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700179
180 fclose(out);
181 return NO_ERROR;
182}
183
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700184/**
185 * Write debugging data about statsd in text format.
186 */
187void StatsService::dump_impl(FILE* out) {
188 mConfigManager->Dump(out);
189}
190
191/**
192 * Implementation of the adb shell cmd stats command.
193 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700194status_t StatsService::command(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700195 // TODO: Permission check
196
197 const int argCount = args.size();
198 if (argCount >= 1) {
199 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700200 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700201 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700202 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700203
204 // adb shell cmd stats print-stats-log
205 if (!args[0].compare(String8("print-stats-log")) && args.size() > 1) {
206 return cmd_print_stats_log(out, args);
207 }
208
David Chende701692017-10-05 13:16:02 -0700209 if (!args[0].compare(String8("print-uid-map"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700210 return cmd_print_uid_map(out);
David Chende701692017-10-05 13:16:02 -0700211 }
Yao Chen729093d2017-10-16 10:33:26 -0700212
213 if (!args[0].compare(String8("dump-report"))) {
214 return cmd_dump_report(out, err, args);
215 }
David Chen1481fe12017-10-16 13:16:34 -0700216
217 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
218 return cmd_print_pulled_metrics(out, args);
219 }
David Chenadaf8b32017-11-03 15:42:08 -0700220
221 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800222 return cmd_trigger_broadcast(out, args);
223 }
224
225 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800226 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700227 }
yro87d983c2017-11-14 21:31:43 -0800228
229 if (!args[0].compare(String8("clear-config"))) {
230 return cmd_remove_config_files(out);
231 }
Yao Chen8d9989b2017-11-18 18:54:50 -0800232
233 if (!args[0].compare(String8("meminfo"))) {
234 return cmd_dump_memory_info(out);
235 }
yro947fbce2017-11-15 22:50:23 -0800236
237 if (!args[0].compare(String8("write-to-disk"))) {
238 return cmd_write_data_to_disk(out);
239 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700240 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700241
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700242 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700243 return NO_ERROR;
244}
245
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700246void StatsService::print_cmd_help(FILE* out) {
247 fprintf(out,
248 "usage: adb shell cmd stats print-stats-log [tag_required] "
249 "[timestamp_nsec_optional]\n");
250 fprintf(out, "\n");
251 fprintf(out, "\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800252 fprintf(out, "usage: adb shell cmd stats meminfo\n");
253 fprintf(out, "\n");
254 fprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
255 fprintf(out, " # adb shell stop\n");
256 fprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
257 fprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
258 fprintf(out, " # adb shell start\n");
259 fprintf(out, "\n");
260 fprintf(out, "\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700261 fprintf(out, "usage: adb shell cmd stats print-uid-map \n");
262 fprintf(out, "\n");
263 fprintf(out, " Prints the UID, app name, version mapping.\n");
264 fprintf(out, "\n");
265 fprintf(out, "\n");
yro87d983c2017-11-14 21:31:43 -0800266 fprintf(out, "usage: adb shell cmd stats clear-config \n");
267 fprintf(out, "\n");
268 fprintf(out, " Removes all configs from disk.\n");
269 fprintf(out, "\n");
270 fprintf(out, "\n");
yro3fca5ba2017-11-17 13:22:52 -0800271 fprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
David Chen1481fe12017-10-16 13:16:34 -0700272 fprintf(out, "\n");
273 fprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
274 fprintf(out, "\n");
275 fprintf(out, "\n");
yro947fbce2017-11-15 22:50:23 -0800276 fprintf(out, "usage: adb shell cmd stats write-to-disk \n");
277 fprintf(out, "\n");
278 fprintf(out, " Flushes all data on memory to disk.\n");
279 fprintf(out, "\n");
280 fprintf(out, "\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700281 fprintf(out, "usage: adb shell cmd stats config remove [UID] NAME\n");
282 fprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
283 fprintf(out, "\n");
284 fprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
285 fprintf(out, " wire-encoded protobuf format and passed via stdin.\n");
286 fprintf(out, "\n");
287 fprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
288 fprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
289 fprintf(out, " uid is used.\n");
290 fprintf(out, " NAME The per-uid name to use\n");
Yao Chen5154a372017-10-30 22:57:06 -0700291 fprintf(out, "\n");
292 fprintf(out, "\n");
293 fprintf(out, "usage: adb shell cmd stats dump-report [UID] NAME\n");
294 fprintf(out, " Dump all metric data for a configuration.\n");
295 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
296 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
297 fprintf(out, " calling uid is used.\n");
298 fprintf(out, " NAME The name of the configuration\n");
David Chenadaf8b32017-11-03 15:42:08 -0700299 fprintf(out, "\n");
300 fprintf(out, "\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800301 fprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
302 fprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
303 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
304 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
305 fprintf(out, " calling uid is used.\n");
306 fprintf(out, " NAME The name of the configuration\n");
307 fprintf(out, "\n");
308 fprintf(out, "\n");
Yao Chenb3561512017-11-21 18:07:17 -0800309 fprintf(out, "usage: adb shell cmd stats print-stats [reset]\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800310 fprintf(out, " Prints some basic stats.\n");
Yao Chenb3561512017-11-21 18:07:17 -0800311 fprintf(out, " reset: 1 to reset the statsd stats. default=0.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700312}
313
David Chen1d7b0cd2017-11-15 14:20:04 -0800314status_t StatsService::cmd_trigger_broadcast(FILE* out, Vector<String8>& args) {
315 string name;
316 bool good = false;
317 int uid;
318 const int argCount = args.size();
319 if (argCount == 2) {
320 // Automatically pick the UID
321 uid = IPCThreadState::self()->getCallingUid();
322 // TODO: What if this isn't a binder call? Should we fail?
323 name.assign(args[1].c_str(), args[1].size());
324 good = true;
325 } else if (argCount == 3) {
326 // If it's a userdebug or eng build, then the shell user can
327 // impersonate other uids.
328 if (mEngBuild) {
329 const char* s = args[1].c_str();
330 if (*s != '\0') {
331 char* end = NULL;
332 uid = strtol(s, &end, 0);
333 if (*end == '\0') {
334 name.assign(args[2].c_str(), args[2].size());
335 good = true;
336 }
337 }
338 } else {
339 fprintf(out,
340 "The metrics can only be dumped for other UIDs on eng or userdebug "
341 "builds.\n");
342 }
343 }
344 if (!good) {
345 print_cmd_help(out);
346 return UNKNOWN_ERROR;
347 }
348 auto receiver = mConfigManager->GetConfigReceiver(ConfigKey(uid, name));
yro4d889e62017-11-17 15:44:48 -0800349 sp<IStatsCompanionService> sc = getStatsCompanionService();
350 if (sc != nullptr) {
351 sc->sendBroadcast(String16(receiver.first.c_str()), String16(receiver.second.c_str()));
352 ALOGD("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
353 args[2].c_str());
354 } else {
355 ALOGD("Could not access statsCompanion");
356 }
357
David Chenadaf8b32017-11-03 15:42:08 -0700358 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700359}
360
361status_t StatsService::cmd_config(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
362 const int argCount = args.size();
363 if (argCount >= 2) {
364 if (args[1] == "update" || args[1] == "remove") {
365 bool good = false;
366 int uid = -1;
367 string name;
368
369 if (argCount == 3) {
370 // Automatically pick the UID
371 uid = IPCThreadState::self()->getCallingUid();
372 // TODO: What if this isn't a binder call? Should we fail?
373 name.assign(args[2].c_str(), args[2].size());
374 good = true;
375 } else if (argCount == 4) {
376 // If it's a userdebug or eng build, then the shell user can
377 // impersonate other uids.
378 if (mEngBuild) {
379 const char* s = args[2].c_str();
380 if (*s != '\0') {
381 char* end = NULL;
382 uid = strtol(s, &end, 0);
383 if (*end == '\0') {
384 name.assign(args[3].c_str(), args[3].size());
385 good = true;
386 }
387 }
388 } else {
Yao Chen729093d2017-10-16 10:33:26 -0700389 fprintf(err,
390 "The config can only be set for other UIDs on eng or userdebug "
391 "builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700392 }
393 }
394
395 if (!good) {
396 // If arg parsing failed, print the help text and return an error.
397 print_cmd_help(out);
398 return UNKNOWN_ERROR;
399 }
400
401 if (args[1] == "update") {
402 // Read stream into buffer.
403 string buffer;
404 if (!android::base::ReadFdToString(fileno(in), &buffer)) {
405 fprintf(err, "Error reading stream for StatsConfig.\n");
406 return UNKNOWN_ERROR;
407 }
408
409 // Parse buffer.
410 StatsdConfig config;
411 if (!config.ParseFromString(buffer)) {
412 fprintf(err, "Error parsing proto stream for StatsConfig.\n");
413 return UNKNOWN_ERROR;
414 }
415
416 // Add / update the config.
417 mConfigManager->UpdateConfig(ConfigKey(uid, name), config);
418 } else {
419 // Remove the config.
420 mConfigManager->RemoveConfig(ConfigKey(uid, name));
421 }
422
423 return NO_ERROR;
424 }
David Chen0656b7a2017-09-13 15:53:39 -0700425 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700426 print_cmd_help(out);
427 return UNKNOWN_ERROR;
428}
429
Yao Chen729093d2017-10-16 10:33:26 -0700430status_t StatsService::cmd_dump_report(FILE* out, FILE* err, const Vector<String8>& args) {
431 if (mProcessor != nullptr) {
432 const int argCount = args.size();
433 bool good = false;
434 int uid;
435 string name;
436 if (argCount == 2) {
437 // Automatically pick the UID
438 uid = IPCThreadState::self()->getCallingUid();
439 // TODO: What if this isn't a binder call? Should we fail?
Yao Chen5154a372017-10-30 22:57:06 -0700440 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700441 good = true;
442 } else if (argCount == 3) {
443 // If it's a userdebug or eng build, then the shell user can
444 // impersonate other uids.
445 if (mEngBuild) {
446 const char* s = args[1].c_str();
447 if (*s != '\0') {
448 char* end = NULL;
449 uid = strtol(s, &end, 0);
450 if (*end == '\0') {
451 name.assign(args[2].c_str(), args[2].size());
452 good = true;
453 }
454 }
455 } else {
456 fprintf(out,
457 "The metrics can only be dumped for other UIDs on eng or userdebug "
458 "builds.\n");
459 }
460 }
461 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800462 vector<uint8_t> data;
463 mProcessor->onDumpReport(ConfigKey(uid, name), &data);
Yao Chen729093d2017-10-16 10:33:26 -0700464 // TODO: print the returned StatsLogReport to file instead of printing to logcat.
465 fprintf(out, "Dump report for Config [%d,%s]\n", uid, name.c_str());
466 fprintf(out, "See the StatsLogReport in logcat...\n");
467 return android::OK;
468 } else {
469 // If arg parsing failed, print the help text and return an error.
470 print_cmd_help(out);
471 return UNKNOWN_ERROR;
472 }
473 } else {
474 fprintf(out, "Log processor does not exist...\n");
475 return UNKNOWN_ERROR;
476 }
477}
478
Yao Chenb3561512017-11-21 18:07:17 -0800479status_t StatsService::cmd_print_stats(FILE* out, const Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800480 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
481 for (const ConfigKey& key : configs) {
482 fprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
483 mProcessor->GetMetricsSize(key));
484 }
Yao Chenb3561512017-11-21 18:07:17 -0800485 fprintf(out, "Detailed statsd stats in logcat...");
486 StatsdStats& statsdStats = StatsdStats::getInstance();
487 bool reset = false;
488 if (args.size() > 1) {
489 reset = strtol(args[1].string(), NULL, 10);
490 }
Yao Chen69f1baf2017-11-27 17:25:36 -0800491 vector<uint8_t> output;
Yao Chenb3561512017-11-21 18:07:17 -0800492 statsdStats.dumpStats(&output, reset);
David Chen1d7b0cd2017-11-15 14:20:04 -0800493 return NO_ERROR;
494}
495
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700496status_t StatsService::cmd_print_stats_log(FILE* out, const Vector<String8>& args) {
497 long msec = 0;
498
499 if (args.size() > 2) {
500 msec = strtol(args[2].string(), NULL, 10);
David Chen0656b7a2017-09-13 15:53:39 -0700501 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700502 return DropboxReader::readStatsLogs(out, args[1].string(), msec);
503}
504
505status_t StatsService::cmd_print_uid_map(FILE* out) {
506 mUidMap->printUidMap(out);
507 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700508}
509
yro947fbce2017-11-15 22:50:23 -0800510status_t StatsService::cmd_write_data_to_disk(FILE* out) {
511 fprintf(out, "Writing data to disk\n");
512 mProcessor->WriteDataToDisk();
513 return NO_ERROR;
514}
515
David Chen1481fe12017-10-16 13:16:34 -0700516status_t StatsService::cmd_print_pulled_metrics(FILE* out, const Vector<String8>& args) {
517 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700518 vector<shared_ptr<LogEvent> > stats;
519 if (mStatsPullerManager.Pull(s, &stats)) {
520 for (const auto& it : stats) {
521 fprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
522 }
523 fprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
524 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700525 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700526 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700527}
528
yro87d983c2017-11-14 21:31:43 -0800529status_t StatsService::cmd_remove_config_files(FILE* out) {
530 fprintf(out, "Trying to remove config files...\n");
yro947fbce2017-11-15 22:50:23 -0800531 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800532 return NO_ERROR;
533}
534
Yao Chen8d9989b2017-11-18 18:54:50 -0800535status_t StatsService::cmd_dump_memory_info(FILE* out) {
536 std::string s = dumpMemInfo(100);
537 fprintf(out, "Memory Info\n");
538 fprintf(out, "%s", s.c_str());
539 return NO_ERROR;
540}
541
David Chende701692017-10-05 13:16:02 -0700542Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int32_t>& version,
543 const vector<String16>& app) {
544 if (DEBUG) ALOGD("StatsService::informAllUidData was called");
545
546 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
547 return Status::fromExceptionCode(Status::EX_SECURITY,
548 "Only system uid can call informAllUidData");
549 }
550
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700551 mUidMap->updateMap(uid, version, app);
David Chende701692017-10-05 13:16:02 -0700552 if (DEBUG) ALOGD("StatsService::informAllUidData succeeded");
553
554 return Status::ok();
555}
556
557Status StatsService::informOnePackage(const String16& app, int32_t uid, int32_t version) {
558 if (DEBUG) ALOGD("StatsService::informOnePackage was called");
559
560 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
561 return Status::fromExceptionCode(Status::EX_SECURITY,
562 "Only system uid can call informOnePackage");
563 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700564 mUidMap->updateApp(app, uid, version);
David Chende701692017-10-05 13:16:02 -0700565 return Status::ok();
566}
567
568Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
569 if (DEBUG) ALOGD("StatsService::informOnePackageRemoved was called");
570
571 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
572 return Status::fromExceptionCode(Status::EX_SECURITY,
573 "Only system uid can call informOnePackageRemoved");
574 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700575 mUidMap->removeApp(app, uid);
David Chende701692017-10-05 13:16:02 -0700576 return Status::ok();
577}
578
Yao Chenef99c4f2017-09-22 16:26:54 -0700579Status StatsService::informAnomalyAlarmFired() {
Bookatzb487b552017-09-18 11:26:01 -0700580 if (DEBUG) ALOGD("StatsService::informAnomalyAlarmFired was called");
Bookatz1b0b1142017-09-08 11:58:42 -0700581
582 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
583 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700584 "Only system uid can call informAnomalyAlarmFired");
Bookatz1b0b1142017-09-08 11:58:42 -0700585 }
586
Bookatzb487b552017-09-18 11:26:01 -0700587 if (DEBUG) ALOGD("StatsService::informAnomalyAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700588 // TODO: check through all counters/timers and see if an anomaly has indeed occurred.
Yangster-mace2cd6d52017-11-09 20:38:30 -0800589 uint64_t currentTimeNs = time(nullptr) * NS_PER_SEC;
590 std::unordered_set<sp<const AnomalyAlarm>, SpHash<AnomalyAlarm>> anomalySet =
591 mAnomalyMonitor->onAlarmFired(currentTimeNs);
592 mProcessor->onAnomalyAlarmFired(currentTimeNs, anomalySet);
Bookatz1b0b1142017-09-08 11:58:42 -0700593 return Status::ok();
594}
595
Yao Chenef99c4f2017-09-22 16:26:54 -0700596Status StatsService::informPollAlarmFired() {
Bookatzb487b552017-09-18 11:26:01 -0700597 if (DEBUG) ALOGD("StatsService::informPollAlarmFired was called");
Bookatz1b0b1142017-09-08 11:58:42 -0700598
599 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
600 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700601 "Only system uid can call informPollAlarmFired");
Bookatz1b0b1142017-09-08 11:58:42 -0700602 }
603
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700604 mStatsPullerManager.OnAlarmFired();
Chenjie Yub3dda412017-10-24 13:41:59 -0700605
Bookatzb487b552017-09-18 11:26:01 -0700606 if (DEBUG) ALOGD("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700607
608 return Status::ok();
609}
610
Yao Chenef99c4f2017-09-22 16:26:54 -0700611Status StatsService::systemRunning() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700612 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
613 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700614 "Only system uid can call systemRunning");
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700615 }
616
617 // When system_server is up and running, schedule the dropbox task to run.
618 ALOGD("StatsService::systemRunning");
619
Bookatzb487b552017-09-18 11:26:01 -0700620 sayHiToStatsCompanion();
621
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700622 return Status::ok();
623}
624
yro947fbce2017-11-15 22:50:23 -0800625Status StatsService::writeDataToDisk() {
626 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
627 return Status::fromExceptionCode(Status::EX_SECURITY,
628 "Only system uid can call systemRunning");
629 }
630
631 ALOGD("StatsService::writeDataToDisk");
632
633 mProcessor->WriteDataToDisk();
634
635 return Status::ok();
636}
637
Yao Chenef99c4f2017-09-22 16:26:54 -0700638void StatsService::sayHiToStatsCompanion() {
639 // TODO: This method needs to be private. It is temporarily public and unsecured for testing
640 // purposes.
Bookatzb487b552017-09-18 11:26:01 -0700641 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
642 if (statsCompanion != nullptr) {
643 if (DEBUG) ALOGD("Telling statsCompanion that statsd is ready");
644 statsCompanion->statsdReady();
645 } else {
646 if (DEBUG) ALOGD("Could not access statsCompanion");
647 }
648}
649
Yao Chenef99c4f2017-09-22 16:26:54 -0700650sp<IStatsCompanionService> StatsService::getStatsCompanionService() {
Bookatz906a35c2017-09-20 15:26:44 -0700651 sp<IStatsCompanionService> statsCompanion = nullptr;
652 // Get statscompanion service from service manager
653 const sp<IServiceManager> sm(defaultServiceManager());
654 if (sm != nullptr) {
655 const String16 name("statscompanion");
656 statsCompanion = interface_cast<IStatsCompanionService>(sm->checkService(name));
657 if (statsCompanion == nullptr) {
658 ALOGW("statscompanion service unavailable!");
659 return nullptr;
660 }
661 }
662 return statsCompanion;
663}
664
Yao Chenef99c4f2017-09-22 16:26:54 -0700665Status StatsService::statsCompanionReady() {
Bookatzb487b552017-09-18 11:26:01 -0700666 if (DEBUG) ALOGD("StatsService::statsCompanionReady was called");
667
668 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
669 return Status::fromExceptionCode(Status::EX_SECURITY,
670 "Only system uid can call statsCompanionReady");
671 }
672
673 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
674 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700675 return Status::fromExceptionCode(
676 Status::EX_NULL_POINTER,
677 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700678 }
679 if (DEBUG) ALOGD("StatsService::statsCompanionReady linking to statsCompanion.");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700680 IInterface::asBinder(statsCompanion)->linkToDeath(new CompanionDeathRecipient(mAnomalyMonitor));
Bookatzb487b552017-09-18 11:26:01 -0700681 mAnomalyMonitor->setStatsCompanionService(statsCompanion);
682
683 return Status::ok();
684}
685
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700686void StatsService::Startup() {
687 mConfigManager->Startup();
Bookatz906a35c2017-09-20 15:26:44 -0700688}
689
Joe Onoratoc4dfae52017-10-17 23:38:21 -0700690void StatsService::OnLogEvent(const LogEvent& event) {
691 mProcessor->OnLogEvent(event);
Bookatz906a35c2017-09-20 15:26:44 -0700692}
693
Yangster7c334a12017-11-22 14:24:24 -0800694Status StatsService::getData(const String16& key, vector<uint8_t>* output) {
David Chenadaf8b32017-11-03 15:42:08 -0700695 IPCThreadState* ipc = IPCThreadState::self();
David Chen1d7b0cd2017-11-15 14:20:04 -0800696 ALOGD("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(),
697 ipc->getCallingUid());
Yao Chen7ee94152017-11-17 09:44:40 -0800698 if (checkCallingPermission(String16(kPermissionDump))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800699 string keyStr = string(String8(key).string());
700 ConfigKey configKey(ipc->getCallingUid(), keyStr);
701 mProcessor->onDumpReport(configKey, output);
David Chenadaf8b32017-11-03 15:42:08 -0700702 return Status::ok();
703 } else {
704 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
705 }
yro31eb67b2017-10-24 13:33:21 -0700706}
707
David Chenadaf8b32017-11-03 15:42:08 -0700708Status StatsService::addConfiguration(const String16& key,
709 const vector <uint8_t>& config,
710 const String16& package, const String16& cls,
711 bool* success) {
712 IPCThreadState* ipc = IPCThreadState::self();
Yao Chen7ee94152017-11-17 09:44:40 -0800713 if (checkCallingPermission(String16(kPermissionDump))) {
David Chenadaf8b32017-11-03 15:42:08 -0700714 string keyString = string(String8(key).string());
David Chen1d7b0cd2017-11-15 14:20:04 -0800715 ConfigKey configKey(ipc->getCallingUid(), keyString);
David Chenadaf8b32017-11-03 15:42:08 -0700716 StatsdConfig cfg;
717 cfg.ParseFromArray(&config[0], config.size());
718 mConfigManager->UpdateConfig(configKey, cfg);
719 mConfigManager->SetConfigReceiver(configKey, string(String8(package).string()),
720 string(String8(cls).string()));
721 *success = true;
722 return Status::ok();
723 } else {
724 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
yro31eb67b2017-10-24 13:33:21 -0700725 }
yro31eb67b2017-10-24 13:33:21 -0700726}
727
David Chenadaf8b32017-11-03 15:42:08 -0700728Status StatsService::removeConfiguration(const String16& key, bool* success) {
729 IPCThreadState* ipc = IPCThreadState::self();
Yao Chen7ee94152017-11-17 09:44:40 -0800730 if (checkCallingPermission(String16(kPermissionDump))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800731 string keyStr = string(String8(key).string());
732 mConfigManager->RemoveConfig(ConfigKey(ipc->getCallingUid(), keyStr));
David Chenadaf8b32017-11-03 15:42:08 -0700733 return Status::ok();
734 } else {
735 *success = false;
736 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
yro31eb67b2017-10-24 13:33:21 -0700737 }
yro31eb67b2017-10-24 13:33:21 -0700738}
739
David Chen1d7b0cd2017-11-15 14:20:04 -0800740void StatsService::binderDied(const wp <IBinder>& who) {
yro31eb67b2017-10-24 13:33:21 -0700741}
742
Yao Chenef99c4f2017-09-22 16:26:54 -0700743} // namespace statsd
744} // namespace os
745} // namespace android