blob: f2ea943f3aa2f3a6915e7e99e42f84b0c4af6e07 [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");
Chenjie Yub236c862017-11-28 22:20:44 -0800293 fprintf(out, "usage: adb shell cmd stats dump-report [UID] NAME [--proto]\n");
Yao Chen5154a372017-10-30 22:57:06 -0700294 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");
Chenjie Yub236c862017-11-28 22:20:44 -0800299 fprintf(out, " --proto Print proto binary.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700300 fprintf(out, "\n");
301 fprintf(out, "\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800302 fprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
303 fprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
304 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
305 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
306 fprintf(out, " calling uid is used.\n");
307 fprintf(out, " NAME The name of the configuration\n");
308 fprintf(out, "\n");
309 fprintf(out, "\n");
Yao Chenb3561512017-11-21 18:07:17 -0800310 fprintf(out, "usage: adb shell cmd stats print-stats [reset]\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800311 fprintf(out, " Prints some basic stats.\n");
Yao Chenb3561512017-11-21 18:07:17 -0800312 fprintf(out, " reset: 1 to reset the statsd stats. default=0.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700313}
314
David Chen1d7b0cd2017-11-15 14:20:04 -0800315status_t StatsService::cmd_trigger_broadcast(FILE* out, Vector<String8>& args) {
316 string name;
317 bool good = false;
318 int uid;
319 const int argCount = args.size();
320 if (argCount == 2) {
321 // Automatically pick the UID
322 uid = IPCThreadState::self()->getCallingUid();
323 // TODO: What if this isn't a binder call? Should we fail?
324 name.assign(args[1].c_str(), args[1].size());
325 good = true;
326 } else if (argCount == 3) {
327 // If it's a userdebug or eng build, then the shell user can
328 // impersonate other uids.
329 if (mEngBuild) {
330 const char* s = args[1].c_str();
331 if (*s != '\0') {
332 char* end = NULL;
333 uid = strtol(s, &end, 0);
334 if (*end == '\0') {
335 name.assign(args[2].c_str(), args[2].size());
336 good = true;
337 }
338 }
339 } else {
340 fprintf(out,
341 "The metrics can only be dumped for other UIDs on eng or userdebug "
342 "builds.\n");
343 }
344 }
345 if (!good) {
346 print_cmd_help(out);
347 return UNKNOWN_ERROR;
348 }
349 auto receiver = mConfigManager->GetConfigReceiver(ConfigKey(uid, name));
yro4d889e62017-11-17 15:44:48 -0800350 sp<IStatsCompanionService> sc = getStatsCompanionService();
351 if (sc != nullptr) {
352 sc->sendBroadcast(String16(receiver.first.c_str()), String16(receiver.second.c_str()));
353 ALOGD("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
354 args[2].c_str());
355 } else {
356 ALOGD("Could not access statsCompanion");
357 }
358
David Chenadaf8b32017-11-03 15:42:08 -0700359 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700360}
361
362status_t StatsService::cmd_config(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
363 const int argCount = args.size();
364 if (argCount >= 2) {
365 if (args[1] == "update" || args[1] == "remove") {
366 bool good = false;
367 int uid = -1;
368 string name;
369
370 if (argCount == 3) {
371 // Automatically pick the UID
372 uid = IPCThreadState::self()->getCallingUid();
373 // TODO: What if this isn't a binder call? Should we fail?
374 name.assign(args[2].c_str(), args[2].size());
375 good = true;
376 } else if (argCount == 4) {
377 // If it's a userdebug or eng build, then the shell user can
378 // impersonate other uids.
379 if (mEngBuild) {
380 const char* s = args[2].c_str();
381 if (*s != '\0') {
382 char* end = NULL;
383 uid = strtol(s, &end, 0);
384 if (*end == '\0') {
385 name.assign(args[3].c_str(), args[3].size());
386 good = true;
387 }
388 }
389 } else {
Yao Chen729093d2017-10-16 10:33:26 -0700390 fprintf(err,
391 "The config can only be set for other UIDs on eng or userdebug "
392 "builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700393 }
394 }
395
396 if (!good) {
397 // If arg parsing failed, print the help text and return an error.
398 print_cmd_help(out);
399 return UNKNOWN_ERROR;
400 }
401
402 if (args[1] == "update") {
403 // Read stream into buffer.
404 string buffer;
405 if (!android::base::ReadFdToString(fileno(in), &buffer)) {
406 fprintf(err, "Error reading stream for StatsConfig.\n");
407 return UNKNOWN_ERROR;
408 }
409
410 // Parse buffer.
411 StatsdConfig config;
412 if (!config.ParseFromString(buffer)) {
413 fprintf(err, "Error parsing proto stream for StatsConfig.\n");
414 return UNKNOWN_ERROR;
415 }
416
417 // Add / update the config.
418 mConfigManager->UpdateConfig(ConfigKey(uid, name), config);
419 } else {
420 // Remove the config.
421 mConfigManager->RemoveConfig(ConfigKey(uid, name));
422 }
423
424 return NO_ERROR;
425 }
David Chen0656b7a2017-09-13 15:53:39 -0700426 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700427 print_cmd_help(out);
428 return UNKNOWN_ERROR;
429}
430
Yao Chen729093d2017-10-16 10:33:26 -0700431status_t StatsService::cmd_dump_report(FILE* out, FILE* err, const Vector<String8>& args) {
432 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800433 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700434 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800435 bool proto = false;
Yao Chen729093d2017-10-16 10:33:26 -0700436 int uid;
437 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800438 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
439 proto = true;
440 argCount -= 1;
441 }
Yao Chen729093d2017-10-16 10:33:26 -0700442 if (argCount == 2) {
443 // Automatically pick the UID
444 uid = IPCThreadState::self()->getCallingUid();
445 // TODO: What if this isn't a binder call? Should we fail?
Yao Chen5154a372017-10-30 22:57:06 -0700446 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700447 good = true;
448 } else if (argCount == 3) {
449 // If it's a userdebug or eng build, then the shell user can
450 // impersonate other uids.
451 if (mEngBuild) {
452 const char* s = args[1].c_str();
453 if (*s != '\0') {
454 char* end = NULL;
455 uid = strtol(s, &end, 0);
456 if (*end == '\0') {
457 name.assign(args[2].c_str(), args[2].size());
458 good = true;
459 }
460 }
461 } else {
462 fprintf(out,
463 "The metrics can only be dumped for other UIDs on eng or userdebug "
464 "builds.\n");
465 }
466 }
467 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800468 vector<uint8_t> data;
469 mProcessor->onDumpReport(ConfigKey(uid, name), &data);
Yao Chen729093d2017-10-16 10:33:26 -0700470 // TODO: print the returned StatsLogReport to file instead of printing to logcat.
Chenjie Yub236c862017-11-28 22:20:44 -0800471 if (proto) {
472 for (size_t i = 0; i < data.size(); i ++) {
473 fprintf(out, "%c", data[i]);
474 }
475 } else {
476 fprintf(out, "Dump report for Config [%d,%s]\n", uid, name.c_str());
477 fprintf(out, "See the StatsLogReport in logcat...\n");
478 }
Yao Chen729093d2017-10-16 10:33:26 -0700479 return android::OK;
480 } else {
481 // If arg parsing failed, print the help text and return an error.
482 print_cmd_help(out);
483 return UNKNOWN_ERROR;
484 }
485 } else {
486 fprintf(out, "Log processor does not exist...\n");
487 return UNKNOWN_ERROR;
488 }
489}
490
Yao Chenb3561512017-11-21 18:07:17 -0800491status_t StatsService::cmd_print_stats(FILE* out, const Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800492 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
493 for (const ConfigKey& key : configs) {
494 fprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
495 mProcessor->GetMetricsSize(key));
496 }
Yao Chenb3561512017-11-21 18:07:17 -0800497 fprintf(out, "Detailed statsd stats in logcat...");
498 StatsdStats& statsdStats = StatsdStats::getInstance();
499 bool reset = false;
500 if (args.size() > 1) {
501 reset = strtol(args[1].string(), NULL, 10);
502 }
Yao Chen69f1baf2017-11-27 17:25:36 -0800503 vector<uint8_t> output;
Yao Chenb3561512017-11-21 18:07:17 -0800504 statsdStats.dumpStats(&output, reset);
David Chen1d7b0cd2017-11-15 14:20:04 -0800505 return NO_ERROR;
506}
507
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700508status_t StatsService::cmd_print_stats_log(FILE* out, const Vector<String8>& args) {
509 long msec = 0;
510
511 if (args.size() > 2) {
512 msec = strtol(args[2].string(), NULL, 10);
David Chen0656b7a2017-09-13 15:53:39 -0700513 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700514 return DropboxReader::readStatsLogs(out, args[1].string(), msec);
515}
516
517status_t StatsService::cmd_print_uid_map(FILE* out) {
518 mUidMap->printUidMap(out);
519 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700520}
521
yro947fbce2017-11-15 22:50:23 -0800522status_t StatsService::cmd_write_data_to_disk(FILE* out) {
523 fprintf(out, "Writing data to disk\n");
524 mProcessor->WriteDataToDisk();
525 return NO_ERROR;
526}
527
David Chen1481fe12017-10-16 13:16:34 -0700528status_t StatsService::cmd_print_pulled_metrics(FILE* out, const Vector<String8>& args) {
529 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700530 vector<shared_ptr<LogEvent> > stats;
531 if (mStatsPullerManager.Pull(s, &stats)) {
532 for (const auto& it : stats) {
533 fprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
534 }
535 fprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
536 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700537 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700538 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700539}
540
yro87d983c2017-11-14 21:31:43 -0800541status_t StatsService::cmd_remove_config_files(FILE* out) {
542 fprintf(out, "Trying to remove config files...\n");
yro947fbce2017-11-15 22:50:23 -0800543 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800544 return NO_ERROR;
545}
546
Yao Chen8d9989b2017-11-18 18:54:50 -0800547status_t StatsService::cmd_dump_memory_info(FILE* out) {
548 std::string s = dumpMemInfo(100);
549 fprintf(out, "Memory Info\n");
550 fprintf(out, "%s", s.c_str());
551 return NO_ERROR;
552}
553
David Chende701692017-10-05 13:16:02 -0700554Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int32_t>& version,
555 const vector<String16>& app) {
556 if (DEBUG) ALOGD("StatsService::informAllUidData was called");
557
558 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
559 return Status::fromExceptionCode(Status::EX_SECURITY,
560 "Only system uid can call informAllUidData");
561 }
562
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700563 mUidMap->updateMap(uid, version, app);
David Chende701692017-10-05 13:16:02 -0700564 if (DEBUG) ALOGD("StatsService::informAllUidData succeeded");
565
566 return Status::ok();
567}
568
569Status StatsService::informOnePackage(const String16& app, int32_t uid, int32_t version) {
570 if (DEBUG) ALOGD("StatsService::informOnePackage was called");
571
572 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
573 return Status::fromExceptionCode(Status::EX_SECURITY,
574 "Only system uid can call informOnePackage");
575 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700576 mUidMap->updateApp(app, uid, version);
David Chende701692017-10-05 13:16:02 -0700577 return Status::ok();
578}
579
580Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
581 if (DEBUG) ALOGD("StatsService::informOnePackageRemoved was called");
582
583 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
584 return Status::fromExceptionCode(Status::EX_SECURITY,
585 "Only system uid can call informOnePackageRemoved");
586 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700587 mUidMap->removeApp(app, uid);
David Chende701692017-10-05 13:16:02 -0700588 return Status::ok();
589}
590
Yao Chenef99c4f2017-09-22 16:26:54 -0700591Status StatsService::informAnomalyAlarmFired() {
Bookatzb487b552017-09-18 11:26:01 -0700592 if (DEBUG) ALOGD("StatsService::informAnomalyAlarmFired was called");
Bookatz1b0b1142017-09-08 11:58:42 -0700593
594 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
595 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700596 "Only system uid can call informAnomalyAlarmFired");
Bookatz1b0b1142017-09-08 11:58:42 -0700597 }
598
Bookatzb487b552017-09-18 11:26:01 -0700599 if (DEBUG) ALOGD("StatsService::informAnomalyAlarmFired succeeded");
Bookatzcc5adef2017-11-21 14:36:23 -0800600 uint64_t currentTimeSec = time(nullptr);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800601 std::unordered_set<sp<const AnomalyAlarm>, SpHash<AnomalyAlarm>> anomalySet =
Bookatzcc5adef2017-11-21 14:36:23 -0800602 mAnomalyMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
603 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, anomalySet);
Bookatz1b0b1142017-09-08 11:58:42 -0700604 return Status::ok();
605}
606
Yao Chenef99c4f2017-09-22 16:26:54 -0700607Status StatsService::informPollAlarmFired() {
Bookatzb487b552017-09-18 11:26:01 -0700608 if (DEBUG) ALOGD("StatsService::informPollAlarmFired was called");
Bookatz1b0b1142017-09-08 11:58:42 -0700609
610 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
611 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700612 "Only system uid can call informPollAlarmFired");
Bookatz1b0b1142017-09-08 11:58:42 -0700613 }
614
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700615 mStatsPullerManager.OnAlarmFired();
Chenjie Yub3dda412017-10-24 13:41:59 -0700616
Bookatzb487b552017-09-18 11:26:01 -0700617 if (DEBUG) ALOGD("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700618
619 return Status::ok();
620}
621
Yao Chenef99c4f2017-09-22 16:26:54 -0700622Status StatsService::systemRunning() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700623 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
624 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700625 "Only system uid can call systemRunning");
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700626 }
627
628 // When system_server is up and running, schedule the dropbox task to run.
629 ALOGD("StatsService::systemRunning");
630
Bookatzb487b552017-09-18 11:26:01 -0700631 sayHiToStatsCompanion();
632
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700633 return Status::ok();
634}
635
yro947fbce2017-11-15 22:50:23 -0800636Status StatsService::writeDataToDisk() {
637 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
638 return Status::fromExceptionCode(Status::EX_SECURITY,
639 "Only system uid can call systemRunning");
640 }
641
642 ALOGD("StatsService::writeDataToDisk");
643
644 mProcessor->WriteDataToDisk();
645
646 return Status::ok();
647}
648
Yao Chenef99c4f2017-09-22 16:26:54 -0700649void StatsService::sayHiToStatsCompanion() {
650 // TODO: This method needs to be private. It is temporarily public and unsecured for testing
651 // purposes.
Bookatzb487b552017-09-18 11:26:01 -0700652 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
653 if (statsCompanion != nullptr) {
654 if (DEBUG) ALOGD("Telling statsCompanion that statsd is ready");
655 statsCompanion->statsdReady();
656 } else {
657 if (DEBUG) ALOGD("Could not access statsCompanion");
658 }
659}
660
Yao Chenef99c4f2017-09-22 16:26:54 -0700661sp<IStatsCompanionService> StatsService::getStatsCompanionService() {
Bookatz906a35c2017-09-20 15:26:44 -0700662 sp<IStatsCompanionService> statsCompanion = nullptr;
663 // Get statscompanion service from service manager
664 const sp<IServiceManager> sm(defaultServiceManager());
665 if (sm != nullptr) {
666 const String16 name("statscompanion");
667 statsCompanion = interface_cast<IStatsCompanionService>(sm->checkService(name));
668 if (statsCompanion == nullptr) {
669 ALOGW("statscompanion service unavailable!");
670 return nullptr;
671 }
672 }
673 return statsCompanion;
674}
675
Yao Chenef99c4f2017-09-22 16:26:54 -0700676Status StatsService::statsCompanionReady() {
Bookatzb487b552017-09-18 11:26:01 -0700677 if (DEBUG) ALOGD("StatsService::statsCompanionReady was called");
678
679 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
680 return Status::fromExceptionCode(Status::EX_SECURITY,
681 "Only system uid can call statsCompanionReady");
682 }
683
684 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
685 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700686 return Status::fromExceptionCode(
687 Status::EX_NULL_POINTER,
688 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700689 }
690 if (DEBUG) ALOGD("StatsService::statsCompanionReady linking to statsCompanion.");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700691 IInterface::asBinder(statsCompanion)->linkToDeath(new CompanionDeathRecipient(mAnomalyMonitor));
Bookatzb487b552017-09-18 11:26:01 -0700692 mAnomalyMonitor->setStatsCompanionService(statsCompanion);
693
694 return Status::ok();
695}
696
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700697void StatsService::Startup() {
698 mConfigManager->Startup();
Bookatz906a35c2017-09-20 15:26:44 -0700699}
700
Joe Onoratoc4dfae52017-10-17 23:38:21 -0700701void StatsService::OnLogEvent(const LogEvent& event) {
702 mProcessor->OnLogEvent(event);
Bookatz906a35c2017-09-20 15:26:44 -0700703}
704
Yangster7c334a12017-11-22 14:24:24 -0800705Status StatsService::getData(const String16& key, vector<uint8_t>* output) {
David Chenadaf8b32017-11-03 15:42:08 -0700706 IPCThreadState* ipc = IPCThreadState::self();
David Chen1d7b0cd2017-11-15 14:20:04 -0800707 ALOGD("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(),
708 ipc->getCallingUid());
Yao Chen7ee94152017-11-17 09:44:40 -0800709 if (checkCallingPermission(String16(kPermissionDump))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800710 string keyStr = string(String8(key).string());
711 ConfigKey configKey(ipc->getCallingUid(), keyStr);
712 mProcessor->onDumpReport(configKey, output);
David Chenadaf8b32017-11-03 15:42:08 -0700713 return Status::ok();
714 } else {
715 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
716 }
yro31eb67b2017-10-24 13:33:21 -0700717}
718
David Chenadaf8b32017-11-03 15:42:08 -0700719Status StatsService::addConfiguration(const String16& key,
720 const vector <uint8_t>& config,
721 const String16& package, const String16& cls,
722 bool* success) {
723 IPCThreadState* ipc = IPCThreadState::self();
Yao Chen7ee94152017-11-17 09:44:40 -0800724 if (checkCallingPermission(String16(kPermissionDump))) {
David Chenadaf8b32017-11-03 15:42:08 -0700725 string keyString = string(String8(key).string());
David Chen1d7b0cd2017-11-15 14:20:04 -0800726 ConfigKey configKey(ipc->getCallingUid(), keyString);
David Chenadaf8b32017-11-03 15:42:08 -0700727 StatsdConfig cfg;
728 cfg.ParseFromArray(&config[0], config.size());
729 mConfigManager->UpdateConfig(configKey, cfg);
730 mConfigManager->SetConfigReceiver(configKey, string(String8(package).string()),
731 string(String8(cls).string()));
732 *success = true;
733 return Status::ok();
734 } else {
735 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
yro31eb67b2017-10-24 13:33:21 -0700736 }
yro31eb67b2017-10-24 13:33:21 -0700737}
738
David Chenadaf8b32017-11-03 15:42:08 -0700739Status StatsService::removeConfiguration(const String16& key, bool* success) {
740 IPCThreadState* ipc = IPCThreadState::self();
Yao Chen7ee94152017-11-17 09:44:40 -0800741 if (checkCallingPermission(String16(kPermissionDump))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800742 string keyStr = string(String8(key).string());
743 mConfigManager->RemoveConfig(ConfigKey(ipc->getCallingUid(), keyStr));
David Chenadaf8b32017-11-03 15:42:08 -0700744 return Status::ok();
745 } else {
746 *success = false;
747 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
yro31eb67b2017-10-24 13:33:21 -0700748 }
yro31eb67b2017-10-24 13:33:21 -0700749}
750
David Chen1d7b0cd2017-11-15 14:20:04 -0800751void StatsService::binderDied(const wp <IBinder>& who) {
yro31eb67b2017-10-24 13:33:21 -0700752}
753
Yao Chenef99c4f2017-09-22 16:26:54 -0700754} // namespace statsd
755} // namespace os
756} // namespace android