blob: ba34e59c0ba1e0fa1ed8d27d4e4ec8cb8479a337 [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
yro74fed972017-11-27 14:42:42 -080017#define DEBUG true // STOPSHIP if 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"
yro947fbce2017-11-15 22:50:23 -080026#include "storage/StorageManager.h"
Bookatzc6977972018-01-16 16:55:05 -080027#include "subscriber/SubscriberReporter.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";
yro03faf092017-12-12 00:17:50 -080049#define STATS_SERVICE_DIR "/data/misc/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);
Bookatzc6977972018-01-16 16:55:05 -080071 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
Joe Onorato9fc9edf2017-10-15 20:08:52 -070072}
73
74// ======================================================================
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070075StatsService::StatsService(const sp<Looper>& handlerLooper)
Bookatz1d0136d2017-12-01 11:13:32 -080076 : mAnomalyMonitor(new AnomalyMonitor(MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS))
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070077{
Joe Onorato9fc9edf2017-10-15 20:08:52 -070078 mUidMap = new UidMap();
79 mConfigManager = new ConfigManager();
Yangster-mac20877162017-12-22 17:19:39 -080080 mProcessor = new StatsLogProcessor(mUidMap, mAnomalyMonitor, time(nullptr), [this](const ConfigKey& key) {
yro947fbce2017-11-15 22:50:23 -080081 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen1d7b0cd2017-11-15 14:20:04 -080082 auto receiver = mConfigManager->GetConfigReceiver(key);
83 if (sc == nullptr) {
yro74fed972017-11-27 14:42:42 -080084 VLOG("Could not find StatsCompanionService");
David Chen1d7b0cd2017-11-15 14:20:04 -080085 } else if (receiver.first.size() == 0) {
yro74fed972017-11-27 14:42:42 -080086 VLOG("Statscompanion could not find a broadcast receiver for %s",
87 key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -080088 } else {
89 sc->sendBroadcast(String16(receiver.first.c_str()),
90 String16(receiver.second.c_str()));
91 }
yro31eb67b2017-10-24 13:33:21 -070092 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -070093
94 mConfigManager->AddListener(mProcessor);
95
96 init_system_properties();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070097}
98
Yao Chenef99c4f2017-09-22 16:26:54 -070099StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700100}
101
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700102void StatsService::init_system_properties() {
103 mEngBuild = false;
104 const prop_info* buildType = __system_property_find("ro.build.type");
105 if (buildType != NULL) {
106 __system_property_read_callback(buildType, init_build_type_callback, this);
107 }
David Chen0656b7a2017-09-13 15:53:39 -0700108}
109
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700110void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
111 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700112 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700113 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
114 }
115}
116
117/**
118 * Implement our own because the default binder implementation isn't
119 * properly handling SHELL_COMMAND_TRANSACTION.
120 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700121status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
122 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700123 status_t err;
124
125 switch (code) {
126 case SHELL_COMMAND_TRANSACTION: {
127 int in = data.readFileDescriptor();
128 int out = data.readFileDescriptor();
129 int err = data.readFileDescriptor();
130 int argc = data.readInt32();
131 Vector<String8> args;
132 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
133 args.add(String8(data.readString16()));
134 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700135 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
136 sp<IResultReceiver> resultReceiver =
137 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700138
139 FILE* fin = fdopen(in, "r");
140 FILE* fout = fdopen(out, "w");
141 FILE* ferr = fdopen(err, "w");
142
143 if (fin == NULL || fout == NULL || ferr == NULL) {
144 resultReceiver->send(NO_MEMORY);
145 } else {
146 err = command(fin, fout, ferr, args);
147 resultReceiver->send(err);
148 }
149
150 if (fin != NULL) {
151 fflush(fin);
152 fclose(fin);
153 }
154 if (fout != NULL) {
155 fflush(fout);
156 fclose(fout);
157 }
158 if (fout != NULL) {
159 fflush(ferr);
160 fclose(ferr);
161 }
162
163 return NO_ERROR;
164 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700165 default: { return BnStatsManager::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700166 }
167}
168
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700169/**
170 * Write debugging data about statsd.
171 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700172status_t StatsService::dump(int fd, const Vector<String16>& args) {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700173 FILE* out = fdopen(fd, "w");
174 if (out == NULL) {
175 return NO_MEMORY; // the fd is already open
176 }
177
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700178 // TODO: Proto format for incident reports
179 dump_impl(out);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700180
181 fclose(out);
182 return NO_ERROR;
183}
184
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700185/**
186 * Write debugging data about statsd in text format.
187 */
188void StatsService::dump_impl(FILE* out) {
189 mConfigManager->Dump(out);
Yao Chenf5acabe2018-01-17 14:10:34 -0800190 StatsdStats::getInstance().dumpStats(out);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700191}
192
193/**
194 * Implementation of the adb shell cmd stats command.
195 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700196status_t StatsService::command(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700197 // TODO: Permission check
198
199 const int argCount = args.size();
200 if (argCount >= 1) {
201 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700202 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700203 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700204 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700205
David Chende701692017-10-05 13:16:02 -0700206 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800207 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700208 }
Yao Chen729093d2017-10-16 10:33:26 -0700209
210 if (!args[0].compare(String8("dump-report"))) {
211 return cmd_dump_report(out, err, args);
212 }
David Chen1481fe12017-10-16 13:16:34 -0700213
214 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
215 return cmd_print_pulled_metrics(out, args);
216 }
David Chenadaf8b32017-11-03 15:42:08 -0700217
218 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800219 return cmd_trigger_broadcast(out, args);
220 }
221
222 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800223 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700224 }
yro87d983c2017-11-14 21:31:43 -0800225
Yao Chen8d9989b2017-11-18 18:54:50 -0800226 if (!args[0].compare(String8("meminfo"))) {
227 return cmd_dump_memory_info(out);
228 }
yro947fbce2017-11-15 22:50:23 -0800229
230 if (!args[0].compare(String8("write-to-disk"))) {
231 return cmd_write_data_to_disk(out);
232 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700233 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700234
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700235 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700236 return NO_ERROR;
237}
238
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700239void StatsService::print_cmd_help(FILE* out) {
240 fprintf(out,
241 "usage: adb shell cmd stats print-stats-log [tag_required] "
242 "[timestamp_nsec_optional]\n");
243 fprintf(out, "\n");
244 fprintf(out, "\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800245 fprintf(out, "usage: adb shell cmd stats meminfo\n");
246 fprintf(out, "\n");
247 fprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
248 fprintf(out, " # adb shell stop\n");
249 fprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
250 fprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
251 fprintf(out, " # adb shell start\n");
252 fprintf(out, "\n");
253 fprintf(out, "\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800254 fprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700255 fprintf(out, "\n");
256 fprintf(out, " Prints the UID, app name, version mapping.\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800257 fprintf(out, " PKG Optional package name to print the uids of the package\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700258 fprintf(out, "\n");
259 fprintf(out, "\n");
yro3fca5ba2017-11-17 13:22:52 -0800260 fprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
David Chen1481fe12017-10-16 13:16:34 -0700261 fprintf(out, "\n");
262 fprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
263 fprintf(out, "\n");
264 fprintf(out, "\n");
yro947fbce2017-11-15 22:50:23 -0800265 fprintf(out, "usage: adb shell cmd stats write-to-disk \n");
266 fprintf(out, "\n");
267 fprintf(out, " Flushes all data on memory to disk.\n");
268 fprintf(out, "\n");
269 fprintf(out, "\n");
yro74fed972017-11-27 14:42:42 -0800270 fprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700271 fprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
272 fprintf(out, "\n");
273 fprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
yro74fed972017-11-27 14:42:42 -0800274 fprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
275 fprintf(out, " provided, then all configs will be removed from memory and disk.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700276 fprintf(out, "\n");
277 fprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
yro74fed972017-11-27 14:42:42 -0800278 fprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700279 fprintf(out, " uid is used.\n");
280 fprintf(out, " NAME The per-uid name to use\n");
Yao Chen5154a3792017-10-30 22:57:06 -0700281 fprintf(out, "\n");
yro74fed972017-11-27 14:42:42 -0800282 fprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
283 fprintf(out, "\n be removed from memory and disk!\n");
Yao Chen5154a3792017-10-30 22:57:06 -0700284 fprintf(out, "\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800285 fprintf(out, "usage: adb shell cmd stats dump-report [UID] NAME [--proto]\n");
Yao Chen5154a3792017-10-30 22:57:06 -0700286 fprintf(out, " Dump all metric data for a configuration.\n");
287 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
288 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
289 fprintf(out, " calling uid is used.\n");
290 fprintf(out, " NAME The name of the configuration\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800291 fprintf(out, " --proto Print proto binary.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700292 fprintf(out, "\n");
293 fprintf(out, "\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800294 fprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
295 fprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
296 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
297 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
298 fprintf(out, " calling uid is used.\n");
299 fprintf(out, " NAME The name of the configuration\n");
300 fprintf(out, "\n");
301 fprintf(out, "\n");
Yao Chenf5acabe2018-01-17 14:10:34 -0800302 fprintf(out, "usage: adb shell cmd stats print-stats\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800303 fprintf(out, " Prints some basic stats.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700304}
305
David Chen1d7b0cd2017-11-15 14:20:04 -0800306status_t StatsService::cmd_trigger_broadcast(FILE* out, Vector<String8>& args) {
307 string name;
308 bool good = false;
309 int uid;
310 const int argCount = args.size();
311 if (argCount == 2) {
312 // Automatically pick the UID
313 uid = IPCThreadState::self()->getCallingUid();
314 // TODO: What if this isn't a binder call? Should we fail?
315 name.assign(args[1].c_str(), args[1].size());
316 good = true;
317 } else if (argCount == 3) {
318 // If it's a userdebug or eng build, then the shell user can
319 // impersonate other uids.
320 if (mEngBuild) {
321 const char* s = args[1].c_str();
322 if (*s != '\0') {
323 char* end = NULL;
324 uid = strtol(s, &end, 0);
325 if (*end == '\0') {
326 name.assign(args[2].c_str(), args[2].size());
327 good = true;
328 }
329 }
330 } else {
331 fprintf(out,
332 "The metrics can only be dumped for other UIDs on eng or userdebug "
333 "builds.\n");
334 }
335 }
336 if (!good) {
337 print_cmd_help(out);
338 return UNKNOWN_ERROR;
339 }
Yangster-mac94e197c2018-01-02 16:03:03 -0800340 auto receiver = mConfigManager->GetConfigReceiver(ConfigKey(uid, StrToInt64(name)));
yro4d889e62017-11-17 15:44:48 -0800341 sp<IStatsCompanionService> sc = getStatsCompanionService();
342 if (sc != nullptr) {
343 sc->sendBroadcast(String16(receiver.first.c_str()), String16(receiver.second.c_str()));
yro74fed972017-11-27 14:42:42 -0800344 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
345 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800346 } else {
yro74fed972017-11-27 14:42:42 -0800347 VLOG("Could not access statsCompanion");
yro4d889e62017-11-17 15:44:48 -0800348 }
349
David Chenadaf8b32017-11-03 15:42:08 -0700350 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700351}
352
353status_t StatsService::cmd_config(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
354 const int argCount = args.size();
355 if (argCount >= 2) {
356 if (args[1] == "update" || args[1] == "remove") {
357 bool good = false;
358 int uid = -1;
359 string name;
360
361 if (argCount == 3) {
362 // Automatically pick the UID
363 uid = IPCThreadState::self()->getCallingUid();
364 // TODO: What if this isn't a binder call? Should we fail?
365 name.assign(args[2].c_str(), args[2].size());
366 good = true;
367 } else if (argCount == 4) {
368 // If it's a userdebug or eng build, then the shell user can
369 // impersonate other uids.
370 if (mEngBuild) {
371 const char* s = args[2].c_str();
372 if (*s != '\0') {
373 char* end = NULL;
374 uid = strtol(s, &end, 0);
375 if (*end == '\0') {
376 name.assign(args[3].c_str(), args[3].size());
377 good = true;
378 }
379 }
380 } else {
Yao Chen729093d2017-10-16 10:33:26 -0700381 fprintf(err,
382 "The config can only be set for other UIDs on eng or userdebug "
383 "builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700384 }
385 }
386
387 if (!good) {
388 // If arg parsing failed, print the help text and return an error.
389 print_cmd_help(out);
390 return UNKNOWN_ERROR;
391 }
392
393 if (args[1] == "update") {
394 // Read stream into buffer.
395 string buffer;
396 if (!android::base::ReadFdToString(fileno(in), &buffer)) {
397 fprintf(err, "Error reading stream for StatsConfig.\n");
398 return UNKNOWN_ERROR;
399 }
400
401 // Parse buffer.
402 StatsdConfig config;
403 if (!config.ParseFromString(buffer)) {
404 fprintf(err, "Error parsing proto stream for StatsConfig.\n");
405 return UNKNOWN_ERROR;
406 }
407
408 // Add / update the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800409 mConfigManager->UpdateConfig(ConfigKey(uid, StrToInt64(name)), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700410 } else {
yro74fed972017-11-27 14:42:42 -0800411 if (argCount == 2) {
412 cmd_remove_all_configs(out);
413 } else {
414 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800415 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800416 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700417 }
418
419 return NO_ERROR;
420 }
David Chen0656b7a2017-09-13 15:53:39 -0700421 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700422 print_cmd_help(out);
423 return UNKNOWN_ERROR;
424}
425
Yao Chen729093d2017-10-16 10:33:26 -0700426status_t StatsService::cmd_dump_report(FILE* out, FILE* err, const Vector<String8>& args) {
427 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800428 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700429 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800430 bool proto = false;
Yao Chen729093d2017-10-16 10:33:26 -0700431 int uid;
432 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800433 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
434 proto = true;
435 argCount -= 1;
436 }
Yao Chen729093d2017-10-16 10:33:26 -0700437 if (argCount == 2) {
438 // Automatically pick the UID
439 uid = IPCThreadState::self()->getCallingUid();
440 // TODO: What if this isn't a binder call? Should we fail?
Yao Chen5154a3792017-10-30 22:57:06 -0700441 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700442 good = true;
443 } else if (argCount == 3) {
444 // If it's a userdebug or eng build, then the shell user can
445 // impersonate other uids.
446 if (mEngBuild) {
447 const char* s = args[1].c_str();
448 if (*s != '\0') {
449 char* end = NULL;
450 uid = strtol(s, &end, 0);
451 if (*end == '\0') {
452 name.assign(args[2].c_str(), args[2].size());
453 good = true;
454 }
455 }
456 } else {
457 fprintf(out,
458 "The metrics can only be dumped for other UIDs on eng or userdebug "
459 "builds.\n");
460 }
461 }
462 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800463 vector<uint8_t> data;
Yangster-mac94e197c2018-01-02 16:03:03 -0800464 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), &data);
Yao Chen729093d2017-10-16 10:33:26 -0700465 // TODO: print the returned StatsLogReport to file instead of printing to logcat.
Chenjie Yub236c862017-11-28 22:20:44 -0800466 if (proto) {
467 for (size_t i = 0; i < data.size(); i ++) {
468 fprintf(out, "%c", data[i]);
469 }
470 } else {
471 fprintf(out, "Dump report for Config [%d,%s]\n", uid, name.c_str());
472 fprintf(out, "See the StatsLogReport in logcat...\n");
473 }
Yao Chen729093d2017-10-16 10:33:26 -0700474 return android::OK;
475 } else {
476 // If arg parsing failed, print the help text and return an error.
477 print_cmd_help(out);
478 return UNKNOWN_ERROR;
479 }
480 } else {
481 fprintf(out, "Log processor does not exist...\n");
482 return UNKNOWN_ERROR;
483 }
484}
485
Yao Chenb3561512017-11-21 18:07:17 -0800486status_t StatsService::cmd_print_stats(FILE* out, const Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800487 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
488 for (const ConfigKey& key : configs) {
489 fprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
490 mProcessor->GetMetricsSize(key));
491 }
Yao Chenb3561512017-11-21 18:07:17 -0800492 StatsdStats& statsdStats = StatsdStats::getInstance();
Yao Chenf5acabe2018-01-17 14:10:34 -0800493 statsdStats.dumpStats(out);
David Chen1d7b0cd2017-11-15 14:20:04 -0800494 return NO_ERROR;
495}
496
Yao Chend10f7b12017-12-18 12:53:50 -0800497status_t StatsService::cmd_print_uid_map(FILE* out, const Vector<String8>& args) {
498 if (args.size() > 1) {
499 string pkg;
500 pkg.assign(args[1].c_str(), args[1].size());
501 auto uids = mUidMap->getAppUid(pkg);
502 fprintf(out, "%s -> [ ", pkg.c_str());
503 for (const auto& uid : uids) {
504 fprintf(out, "%d ", uid);
505 }
506 fprintf(out, "]\n");
507 } else {
508 mUidMap->printUidMap(out);
509 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700510 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700511}
512
yro947fbce2017-11-15 22:50:23 -0800513status_t StatsService::cmd_write_data_to_disk(FILE* out) {
514 fprintf(out, "Writing data to disk\n");
515 mProcessor->WriteDataToDisk();
516 return NO_ERROR;
517}
518
David Chen1481fe12017-10-16 13:16:34 -0700519status_t StatsService::cmd_print_pulled_metrics(FILE* out, const Vector<String8>& args) {
520 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700521 vector<shared_ptr<LogEvent> > stats;
522 if (mStatsPullerManager.Pull(s, &stats)) {
523 for (const auto& it : stats) {
524 fprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
525 }
526 fprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
527 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700528 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700529 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700530}
531
yro74fed972017-11-27 14:42:42 -0800532status_t StatsService::cmd_remove_all_configs(FILE* out) {
533 fprintf(out, "Removing all configs...\n");
534 VLOG("StatsService::cmd_remove_all_configs was called");
535 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800536 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800537 return NO_ERROR;
538}
539
Yao Chen8d9989b2017-11-18 18:54:50 -0800540status_t StatsService::cmd_dump_memory_info(FILE* out) {
541 std::string s = dumpMemInfo(100);
542 fprintf(out, "Memory Info\n");
543 fprintf(out, "%s", s.c_str());
544 return NO_ERROR;
545}
546
Dianne Hackborn3accca02013-09-20 09:32:11 -0700547Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int64_t>& version,
David Chende701692017-10-05 13:16:02 -0700548 const vector<String16>& app) {
yro74fed972017-11-27 14:42:42 -0800549 VLOG("StatsService::informAllUidData was called");
David Chende701692017-10-05 13:16:02 -0700550
551 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
552 return Status::fromExceptionCode(Status::EX_SECURITY,
553 "Only system uid can call informAllUidData");
554 }
555
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700556 mUidMap->updateMap(uid, version, app);
yro74fed972017-11-27 14:42:42 -0800557 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700558
559 return Status::ok();
560}
561
Dianne Hackborn3accca02013-09-20 09:32:11 -0700562Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version) {
yro74fed972017-11-27 14:42:42 -0800563 VLOG("StatsService::informOnePackage was called");
David Chende701692017-10-05 13:16:02 -0700564
565 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
566 return Status::fromExceptionCode(Status::EX_SECURITY,
567 "Only system uid can call informOnePackage");
568 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700569 mUidMap->updateApp(app, uid, version);
David Chende701692017-10-05 13:16:02 -0700570 return Status::ok();
571}
572
573Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
yro74fed972017-11-27 14:42:42 -0800574 VLOG("StatsService::informOnePackageRemoved was called");
David Chende701692017-10-05 13:16:02 -0700575
576 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
577 return Status::fromExceptionCode(Status::EX_SECURITY,
578 "Only system uid can call informOnePackageRemoved");
579 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700580 mUidMap->removeApp(app, uid);
David Chende701692017-10-05 13:16:02 -0700581 return Status::ok();
582}
583
Yao Chenef99c4f2017-09-22 16:26:54 -0700584Status StatsService::informAnomalyAlarmFired() {
yro74fed972017-11-27 14:42:42 -0800585 VLOG("StatsService::informAnomalyAlarmFired was called");
Bookatz1b0b1142017-09-08 11:58:42 -0700586
587 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
588 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700589 "Only system uid can call informAnomalyAlarmFired");
Bookatz1b0b1142017-09-08 11:58:42 -0700590 }
591
yro74fed972017-11-27 14:42:42 -0800592 VLOG("StatsService::informAnomalyAlarmFired succeeded");
Bookatzcc5adef22017-11-21 14:36:23 -0800593 uint64_t currentTimeSec = time(nullptr);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800594 std::unordered_set<sp<const AnomalyAlarm>, SpHash<AnomalyAlarm>> anomalySet =
Bookatzcc5adef22017-11-21 14:36:23 -0800595 mAnomalyMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
596 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, anomalySet);
Bookatz1b0b1142017-09-08 11:58:42 -0700597 return Status::ok();
598}
599
Yao Chenef99c4f2017-09-22 16:26:54 -0700600Status StatsService::informPollAlarmFired() {
yro74fed972017-11-27 14:42:42 -0800601 VLOG("StatsService::informPollAlarmFired was called");
Bookatz1b0b1142017-09-08 11:58:42 -0700602
603 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
604 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700605 "Only system uid can call informPollAlarmFired");
Bookatz1b0b1142017-09-08 11:58:42 -0700606 }
607
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700608 mStatsPullerManager.OnAlarmFired();
Chenjie Yub3dda412017-10-24 13:41:59 -0700609
yro74fed972017-11-27 14:42:42 -0800610 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700611
612 return Status::ok();
613}
614
Yao Chenef99c4f2017-09-22 16:26:54 -0700615Status StatsService::systemRunning() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700616 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
617 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700618 "Only system uid can call systemRunning");
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700619 }
620
621 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800622 VLOG("StatsService::systemRunning");
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700623
Bookatzb487b552017-09-18 11:26:01 -0700624 sayHiToStatsCompanion();
625
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700626 return Status::ok();
627}
628
yro947fbce2017-11-15 22:50:23 -0800629Status StatsService::writeDataToDisk() {
630 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
631 return Status::fromExceptionCode(Status::EX_SECURITY,
632 "Only system uid can call systemRunning");
633 }
634
yro74fed972017-11-27 14:42:42 -0800635 VLOG("StatsService::writeDataToDisk");
yro947fbce2017-11-15 22:50:23 -0800636
637 mProcessor->WriteDataToDisk();
638
639 return Status::ok();
640}
641
Yao Chenef99c4f2017-09-22 16:26:54 -0700642void StatsService::sayHiToStatsCompanion() {
643 // TODO: This method needs to be private. It is temporarily public and unsecured for testing
644 // purposes.
Bookatzb487b552017-09-18 11:26:01 -0700645 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
646 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -0800647 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -0700648 statsCompanion->statsdReady();
649 } else {
yro74fed972017-11-27 14:42:42 -0800650 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -0700651 }
652}
653
Yao Chenef99c4f2017-09-22 16:26:54 -0700654sp<IStatsCompanionService> StatsService::getStatsCompanionService() {
Bookatz906a35c2017-09-20 15:26:44 -0700655 sp<IStatsCompanionService> statsCompanion = nullptr;
656 // Get statscompanion service from service manager
657 const sp<IServiceManager> sm(defaultServiceManager());
658 if (sm != nullptr) {
659 const String16 name("statscompanion");
660 statsCompanion = interface_cast<IStatsCompanionService>(sm->checkService(name));
661 if (statsCompanion == nullptr) {
662 ALOGW("statscompanion service unavailable!");
663 return nullptr;
664 }
665 }
666 return statsCompanion;
667}
668
Yao Chenef99c4f2017-09-22 16:26:54 -0700669Status StatsService::statsCompanionReady() {
yro74fed972017-11-27 14:42:42 -0800670 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -0700671
672 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
673 return Status::fromExceptionCode(Status::EX_SECURITY,
674 "Only system uid can call statsCompanionReady");
675 }
676
677 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
678 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700679 return Status::fromExceptionCode(
680 Status::EX_NULL_POINTER,
681 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700682 }
yro74fed972017-11-27 14:42:42 -0800683 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700684 IInterface::asBinder(statsCompanion)->linkToDeath(new CompanionDeathRecipient(mAnomalyMonitor));
Bookatzb487b552017-09-18 11:26:01 -0700685 mAnomalyMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -0800686 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -0700687
688 return Status::ok();
689}
690
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700691void StatsService::Startup() {
692 mConfigManager->Startup();
Bookatz906a35c2017-09-20 15:26:44 -0700693}
694
Yangster-macd40053e2018-01-09 16:29:22 -0800695void StatsService::OnLogEvent(LogEvent* event) {
Joe Onoratoc4dfae52017-10-17 23:38:21 -0700696 mProcessor->OnLogEvent(event);
Bookatz906a35c2017-09-20 15:26:44 -0700697}
698
Yangster-mac94e197c2018-01-02 16:03:03 -0800699Status StatsService::getData(int64_t key, vector<uint8_t>* output) {
David Chenadaf8b32017-11-03 15:42:08 -0700700 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -0800701 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Yao Chen7ee94152017-11-17 09:44:40 -0800702 if (checkCallingPermission(String16(kPermissionDump))) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800703 ConfigKey configKey(ipc->getCallingUid(), key);
David Chen1d7b0cd2017-11-15 14:20:04 -0800704 mProcessor->onDumpReport(configKey, output);
David Chenadaf8b32017-11-03 15:42:08 -0700705 return Status::ok();
706 } else {
707 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
708 }
yro31eb67b2017-10-24 13:33:21 -0700709}
710
David Chen2e8f3802017-11-22 10:56:48 -0800711Status StatsService::getMetadata(vector<uint8_t>* output) {
712 IPCThreadState* ipc = IPCThreadState::self();
713 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
714 ipc->getCallingUid());
715 if (checkCallingPermission(String16(kPermissionDump))) {
716 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
717 return Status::ok();
718 } else {
719 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
720 }
721}
722
Yangster-mac94e197c2018-01-02 16:03:03 -0800723Status StatsService::addConfiguration(int64_t key,
David Chenadaf8b32017-11-03 15:42:08 -0700724 const vector <uint8_t>& config,
725 const String16& package, const String16& cls,
726 bool* success) {
727 IPCThreadState* ipc = IPCThreadState::self();
Yao Chen7ee94152017-11-17 09:44:40 -0800728 if (checkCallingPermission(String16(kPermissionDump))) {
Yangster-mac94e197c2018-01-02 16:03:03 -0800729 ConfigKey configKey(ipc->getCallingUid(), key);
David Chenadaf8b32017-11-03 15:42:08 -0700730 StatsdConfig cfg;
Yangster-macbbd056a2018-01-22 13:37:02 -0800731 if (config.empty() || !cfg.ParseFromArray(&config[0], config.size())) {
David Chen7d8aa4d2017-12-27 13:37:01 -0800732 *success = false;
733 return Status::ok();
734 }
David Chenadaf8b32017-11-03 15:42:08 -0700735 mConfigManager->UpdateConfig(configKey, cfg);
736 mConfigManager->SetConfigReceiver(configKey, string(String8(package).string()),
737 string(String8(cls).string()));
738 *success = true;
739 return Status::ok();
740 } else {
Yao Chenaa39bc72017-12-01 11:16:50 -0800741 *success = false;
David Chenadaf8b32017-11-03 15:42:08 -0700742 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
yro31eb67b2017-10-24 13:33:21 -0700743 }
yro31eb67b2017-10-24 13:33:21 -0700744}
745
Yangster-mac94e197c2018-01-02 16:03:03 -0800746Status StatsService::removeConfiguration(int64_t key, bool* success) {
David Chenadaf8b32017-11-03 15:42:08 -0700747 IPCThreadState* ipc = IPCThreadState::self();
Yao Chen7ee94152017-11-17 09:44:40 -0800748 if (checkCallingPermission(String16(kPermissionDump))) {
Bookatzc6977972018-01-16 16:55:05 -0800749 ConfigKey configKey(ipc->getCallingUid(), key);
750 mConfigManager->RemoveConfig(configKey);
751 SubscriberReporter::getInstance().removeConfig(configKey);
Yao Chenaa39bc72017-12-01 11:16:50 -0800752 *success = true;
David Chenadaf8b32017-11-03 15:42:08 -0700753 return Status::ok();
754 } else {
755 *success = false;
756 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
yro31eb67b2017-10-24 13:33:21 -0700757 }
yro31eb67b2017-10-24 13:33:21 -0700758}
759
Bookatzc6977972018-01-16 16:55:05 -0800760Status StatsService::setBroadcastSubscriber(int64_t configId,
761 int64_t subscriberId,
762 const sp<android::IBinder>& intentSender,
763 bool* success) {
764 VLOG("StatsService::setBroadcastSubscriber called.");
765 IPCThreadState* ipc = IPCThreadState::self();
766 if (checkCallingPermission(String16(kPermissionDump))) {
767 ConfigKey configKey(ipc->getCallingUid(), configId);
768 SubscriberReporter::getInstance()
769 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
770 *success = true;
771 return Status::ok();
772 } else {
773 *success = false;
774 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
775 }
776}
777
778Status StatsService::unsetBroadcastSubscriber(int64_t configId,
779 int64_t subscriberId,
780 bool* success) {
781 VLOG("StatsService::unsetBroadcastSubscriber called.");
782 IPCThreadState* ipc = IPCThreadState::self();
783 if (checkCallingPermission(String16(kPermissionDump))) {
784 ConfigKey configKey(ipc->getCallingUid(), configId);
785 SubscriberReporter::getInstance()
786 .unsetBroadcastSubscriber(configKey, subscriberId);
787 *success = true;
788 return Status::ok();
789 } else {
790 *success = false;
791 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
792 }
793}
794
795
David Chen1d7b0cd2017-11-15 14:20:04 -0800796void StatsService::binderDied(const wp <IBinder>& who) {
yro31eb67b2017-10-24 13:33:21 -0700797}
798
Yao Chenef99c4f2017-09-22 16:26:54 -0700799} // namespace statsd
800} // namespace os
801} // namespace android