blob: 4dd25391302a117792edd40972a65fe9ed1bf7d7 [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"
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070027
David Chen0656b7a2017-09-13 15:53:39 -070028#include <android-base/file.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070029#include <binder/IPCThreadState.h>
30#include <binder/IServiceManager.h>
yro87d983c2017-11-14 21:31:43 -080031#include <dirent.h>
David Chen0656b7a2017-09-13 15:53:39 -070032#include <frameworks/base/cmds/statsd/src/statsd_config.pb.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070033#include <private/android_filesystem_config.h>
34#include <utils/Looper.h>
Joe Onorato2cbc2cc2017-08-30 17:03:23 -070035#include <utils/String16.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070036#include <stdio.h>
Yao Chen482d2722017-09-12 13:25:43 -070037#include <stdlib.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070038#include <sys/system_properties.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070039#include <unistd.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070040
41using namespace android;
42
Bookatz906a35c2017-09-20 15:26:44 -070043namespace android {
44namespace os {
45namespace statsd {
46
David Chenadaf8b32017-11-03 15:42:08 -070047constexpr const char* kPermissionDump = "android.permission.DUMP";
yro03faf092017-12-12 00:17:50 -080048#define STATS_SERVICE_DIR "/data/misc/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070049
Joe Onorato9fc9edf2017-10-15 20:08:52 -070050// ======================================================================
51/**
52 * Watches for the death of the stats companion (system process).
53 */
54class CompanionDeathRecipient : public IBinder::DeathRecipient {
55public:
56 CompanionDeathRecipient(const sp<AnomalyMonitor>& anomalyMonitor);
57 virtual void binderDied(const wp<IBinder>& who);
58
59private:
60 const sp<AnomalyMonitor> mAnomalyMonitor;
61};
62
63CompanionDeathRecipient::CompanionDeathRecipient(const sp<AnomalyMonitor>& anomalyMonitor)
64 : mAnomalyMonitor(anomalyMonitor) {
65}
66
67void CompanionDeathRecipient::binderDied(const wp<IBinder>& who) {
68 ALOGW("statscompanion service died");
69 mAnomalyMonitor->setStatsCompanionService(nullptr);
70}
71
72// ======================================================================
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070073StatsService::StatsService(const sp<Looper>& handlerLooper)
Bookatz1d0136d2017-12-01 11:13:32 -080074 : mAnomalyMonitor(new AnomalyMonitor(MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS))
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070075{
Joe Onorato9fc9edf2017-10-15 20:08:52 -070076 mUidMap = new UidMap();
77 mConfigManager = new ConfigManager();
Yangster-mace2cd6d52017-11-09 20:38:30 -080078 mProcessor = new StatsLogProcessor(mUidMap, mAnomalyMonitor, [this](const ConfigKey& key) {
yro947fbce2017-11-15 22:50:23 -080079 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen1d7b0cd2017-11-15 14:20:04 -080080 auto receiver = mConfigManager->GetConfigReceiver(key);
81 if (sc == nullptr) {
yro74fed972017-11-27 14:42:42 -080082 VLOG("Could not find StatsCompanionService");
David Chen1d7b0cd2017-11-15 14:20:04 -080083 } else if (receiver.first.size() == 0) {
yro74fed972017-11-27 14:42:42 -080084 VLOG("Statscompanion could not find a broadcast receiver for %s",
85 key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -080086 } else {
87 sc->sendBroadcast(String16(receiver.first.c_str()),
88 String16(receiver.second.c_str()));
89 }
yro31eb67b2017-10-24 13:33:21 -070090 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -070091
92 mConfigManager->AddListener(mProcessor);
93
94 init_system_properties();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070095}
96
Yao Chenef99c4f2017-09-22 16:26:54 -070097StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070098}
99
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700100void StatsService::init_system_properties() {
101 mEngBuild = false;
102 const prop_info* buildType = __system_property_find("ro.build.type");
103 if (buildType != NULL) {
104 __system_property_read_callback(buildType, init_build_type_callback, this);
105 }
David Chen0656b7a2017-09-13 15:53:39 -0700106}
107
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700108void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
109 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700110 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700111 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
112 }
113}
114
115/**
116 * Implement our own because the default binder implementation isn't
117 * properly handling SHELL_COMMAND_TRANSACTION.
118 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700119status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
120 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700121 status_t err;
122
123 switch (code) {
124 case SHELL_COMMAND_TRANSACTION: {
125 int in = data.readFileDescriptor();
126 int out = data.readFileDescriptor();
127 int err = data.readFileDescriptor();
128 int argc = data.readInt32();
129 Vector<String8> args;
130 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
131 args.add(String8(data.readString16()));
132 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700133 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
134 sp<IResultReceiver> resultReceiver =
135 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700136
137 FILE* fin = fdopen(in, "r");
138 FILE* fout = fdopen(out, "w");
139 FILE* ferr = fdopen(err, "w");
140
141 if (fin == NULL || fout == NULL || ferr == NULL) {
142 resultReceiver->send(NO_MEMORY);
143 } else {
144 err = command(fin, fout, ferr, args);
145 resultReceiver->send(err);
146 }
147
148 if (fin != NULL) {
149 fflush(fin);
150 fclose(fin);
151 }
152 if (fout != NULL) {
153 fflush(fout);
154 fclose(fout);
155 }
156 if (fout != NULL) {
157 fflush(ferr);
158 fclose(ferr);
159 }
160
161 return NO_ERROR;
162 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700163 default: { return BnStatsManager::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700164 }
165}
166
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700167/**
168 * Write debugging data about statsd.
169 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700170status_t StatsService::dump(int fd, const Vector<String16>& args) {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700171 FILE* out = fdopen(fd, "w");
172 if (out == NULL) {
173 return NO_MEMORY; // the fd is already open
174 }
175
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700176 // TODO: Proto format for incident reports
177 dump_impl(out);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700178
179 fclose(out);
180 return NO_ERROR;
181}
182
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700183/**
184 * Write debugging data about statsd in text format.
185 */
186void StatsService::dump_impl(FILE* out) {
187 mConfigManager->Dump(out);
188}
189
190/**
191 * Implementation of the adb shell cmd stats command.
192 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700193status_t StatsService::command(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700194 // TODO: Permission check
195
196 const int argCount = args.size();
197 if (argCount >= 1) {
198 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700199 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700200 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700201 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700202
David Chende701692017-10-05 13:16:02 -0700203 if (!args[0].compare(String8("print-uid-map"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700204 return cmd_print_uid_map(out);
David Chende701692017-10-05 13:16:02 -0700205 }
Yao Chen729093d2017-10-16 10:33:26 -0700206
207 if (!args[0].compare(String8("dump-report"))) {
208 return cmd_dump_report(out, err, args);
209 }
David Chen1481fe12017-10-16 13:16:34 -0700210
211 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
212 return cmd_print_pulled_metrics(out, args);
213 }
David Chenadaf8b32017-11-03 15:42:08 -0700214
215 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800216 return cmd_trigger_broadcast(out, args);
217 }
218
219 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800220 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700221 }
yro87d983c2017-11-14 21:31:43 -0800222
Yao Chen8d9989b2017-11-18 18:54:50 -0800223 if (!args[0].compare(String8("meminfo"))) {
224 return cmd_dump_memory_info(out);
225 }
yro947fbce2017-11-15 22:50:23 -0800226
227 if (!args[0].compare(String8("write-to-disk"))) {
228 return cmd_write_data_to_disk(out);
229 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700230 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700231
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700232 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700233 return NO_ERROR;
234}
235
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700236void StatsService::print_cmd_help(FILE* out) {
237 fprintf(out,
238 "usage: adb shell cmd stats print-stats-log [tag_required] "
239 "[timestamp_nsec_optional]\n");
240 fprintf(out, "\n");
241 fprintf(out, "\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800242 fprintf(out, "usage: adb shell cmd stats meminfo\n");
243 fprintf(out, "\n");
244 fprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
245 fprintf(out, " # adb shell stop\n");
246 fprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
247 fprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
248 fprintf(out, " # adb shell start\n");
249 fprintf(out, "\n");
250 fprintf(out, "\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700251 fprintf(out, "usage: adb shell cmd stats print-uid-map \n");
252 fprintf(out, "\n");
253 fprintf(out, " Prints the UID, app name, version mapping.\n");
254 fprintf(out, "\n");
255 fprintf(out, "\n");
yro3fca5ba2017-11-17 13:22:52 -0800256 fprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
David Chen1481fe12017-10-16 13:16:34 -0700257 fprintf(out, "\n");
258 fprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
259 fprintf(out, "\n");
260 fprintf(out, "\n");
yro947fbce2017-11-15 22:50:23 -0800261 fprintf(out, "usage: adb shell cmd stats write-to-disk \n");
262 fprintf(out, "\n");
263 fprintf(out, " Flushes all data on memory to disk.\n");
264 fprintf(out, "\n");
265 fprintf(out, "\n");
yro74fed972017-11-27 14:42:42 -0800266 fprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700267 fprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
268 fprintf(out, "\n");
269 fprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
yro74fed972017-11-27 14:42:42 -0800270 fprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
271 fprintf(out, " provided, then all configs will be removed from memory and disk.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700272 fprintf(out, "\n");
273 fprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
yro74fed972017-11-27 14:42:42 -0800274 fprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700275 fprintf(out, " uid is used.\n");
276 fprintf(out, " NAME The per-uid name to use\n");
Yao Chen5154a3792017-10-30 22:57:06 -0700277 fprintf(out, "\n");
yro74fed972017-11-27 14:42:42 -0800278 fprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
279 fprintf(out, "\n be removed from memory and disk!\n");
Yao Chen5154a3792017-10-30 22:57:06 -0700280 fprintf(out, "\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800281 fprintf(out, "usage: adb shell cmd stats dump-report [UID] NAME [--proto]\n");
Yao Chen5154a3792017-10-30 22:57:06 -0700282 fprintf(out, " Dump all metric data for a configuration.\n");
283 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
284 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
285 fprintf(out, " calling uid is used.\n");
286 fprintf(out, " NAME The name of the configuration\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800287 fprintf(out, " --proto Print proto binary.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700288 fprintf(out, "\n");
289 fprintf(out, "\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800290 fprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
291 fprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
292 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
293 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
294 fprintf(out, " calling uid is used.\n");
295 fprintf(out, " NAME The name of the configuration\n");
296 fprintf(out, "\n");
297 fprintf(out, "\n");
Yao Chenb3561512017-11-21 18:07:17 -0800298 fprintf(out, "usage: adb shell cmd stats print-stats [reset]\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800299 fprintf(out, " Prints some basic stats.\n");
Yao Chenb3561512017-11-21 18:07:17 -0800300 fprintf(out, " reset: 1 to reset the statsd stats. default=0.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700301}
302
David Chen1d7b0cd2017-11-15 14:20:04 -0800303status_t StatsService::cmd_trigger_broadcast(FILE* out, Vector<String8>& args) {
304 string name;
305 bool good = false;
306 int uid;
307 const int argCount = args.size();
308 if (argCount == 2) {
309 // Automatically pick the UID
310 uid = IPCThreadState::self()->getCallingUid();
311 // TODO: What if this isn't a binder call? Should we fail?
312 name.assign(args[1].c_str(), args[1].size());
313 good = true;
314 } else if (argCount == 3) {
315 // If it's a userdebug or eng build, then the shell user can
316 // impersonate other uids.
317 if (mEngBuild) {
318 const char* s = args[1].c_str();
319 if (*s != '\0') {
320 char* end = NULL;
321 uid = strtol(s, &end, 0);
322 if (*end == '\0') {
323 name.assign(args[2].c_str(), args[2].size());
324 good = true;
325 }
326 }
327 } else {
328 fprintf(out,
329 "The metrics can only be dumped for other UIDs on eng or userdebug "
330 "builds.\n");
331 }
332 }
333 if (!good) {
334 print_cmd_help(out);
335 return UNKNOWN_ERROR;
336 }
337 auto receiver = mConfigManager->GetConfigReceiver(ConfigKey(uid, name));
yro4d889e62017-11-17 15:44:48 -0800338 sp<IStatsCompanionService> sc = getStatsCompanionService();
339 if (sc != nullptr) {
340 sc->sendBroadcast(String16(receiver.first.c_str()), String16(receiver.second.c_str()));
yro74fed972017-11-27 14:42:42 -0800341 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
342 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800343 } else {
yro74fed972017-11-27 14:42:42 -0800344 VLOG("Could not access statsCompanion");
yro4d889e62017-11-17 15:44:48 -0800345 }
346
David Chenadaf8b32017-11-03 15:42:08 -0700347 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700348}
349
350status_t StatsService::cmd_config(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
351 const int argCount = args.size();
352 if (argCount >= 2) {
353 if (args[1] == "update" || args[1] == "remove") {
354 bool good = false;
355 int uid = -1;
356 string name;
357
358 if (argCount == 3) {
359 // Automatically pick the UID
360 uid = IPCThreadState::self()->getCallingUid();
361 // TODO: What if this isn't a binder call? Should we fail?
362 name.assign(args[2].c_str(), args[2].size());
363 good = true;
364 } else if (argCount == 4) {
365 // If it's a userdebug or eng build, then the shell user can
366 // impersonate other uids.
367 if (mEngBuild) {
368 const char* s = args[2].c_str();
369 if (*s != '\0') {
370 char* end = NULL;
371 uid = strtol(s, &end, 0);
372 if (*end == '\0') {
373 name.assign(args[3].c_str(), args[3].size());
374 good = true;
375 }
376 }
377 } else {
Yao Chen729093d2017-10-16 10:33:26 -0700378 fprintf(err,
379 "The config can only be set for other UIDs on eng or userdebug "
380 "builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700381 }
382 }
383
384 if (!good) {
385 // If arg parsing failed, print the help text and return an error.
386 print_cmd_help(out);
387 return UNKNOWN_ERROR;
388 }
389
390 if (args[1] == "update") {
391 // Read stream into buffer.
392 string buffer;
393 if (!android::base::ReadFdToString(fileno(in), &buffer)) {
394 fprintf(err, "Error reading stream for StatsConfig.\n");
395 return UNKNOWN_ERROR;
396 }
397
398 // Parse buffer.
399 StatsdConfig config;
400 if (!config.ParseFromString(buffer)) {
401 fprintf(err, "Error parsing proto stream for StatsConfig.\n");
402 return UNKNOWN_ERROR;
403 }
404
405 // Add / update the config.
406 mConfigManager->UpdateConfig(ConfigKey(uid, name), config);
407 } else {
yro74fed972017-11-27 14:42:42 -0800408 if (argCount == 2) {
409 cmd_remove_all_configs(out);
410 } else {
411 // Remove the config.
412 mConfigManager->RemoveConfig(ConfigKey(uid, name));
413 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700414 }
415
416 return NO_ERROR;
417 }
David Chen0656b7a2017-09-13 15:53:39 -0700418 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700419 print_cmd_help(out);
420 return UNKNOWN_ERROR;
421}
422
Yao Chen729093d2017-10-16 10:33:26 -0700423status_t StatsService::cmd_dump_report(FILE* out, FILE* err, const Vector<String8>& args) {
424 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800425 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700426 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800427 bool proto = false;
Yao Chen729093d2017-10-16 10:33:26 -0700428 int uid;
429 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800430 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
431 proto = true;
432 argCount -= 1;
433 }
Yao Chen729093d2017-10-16 10:33:26 -0700434 if (argCount == 2) {
435 // Automatically pick the UID
436 uid = IPCThreadState::self()->getCallingUid();
437 // TODO: What if this isn't a binder call? Should we fail?
Yao Chen5154a3792017-10-30 22:57:06 -0700438 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700439 good = true;
440 } else if (argCount == 3) {
441 // If it's a userdebug or eng build, then the shell user can
442 // impersonate other uids.
443 if (mEngBuild) {
444 const char* s = args[1].c_str();
445 if (*s != '\0') {
446 char* end = NULL;
447 uid = strtol(s, &end, 0);
448 if (*end == '\0') {
449 name.assign(args[2].c_str(), args[2].size());
450 good = true;
451 }
452 }
453 } else {
454 fprintf(out,
455 "The metrics can only be dumped for other UIDs on eng or userdebug "
456 "builds.\n");
457 }
458 }
459 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800460 vector<uint8_t> data;
461 mProcessor->onDumpReport(ConfigKey(uid, name), &data);
Yao Chen729093d2017-10-16 10:33:26 -0700462 // TODO: print the returned StatsLogReport to file instead of printing to logcat.
Chenjie Yub236c862017-11-28 22:20:44 -0800463 if (proto) {
464 for (size_t i = 0; i < data.size(); i ++) {
465 fprintf(out, "%c", data[i]);
466 }
467 } else {
468 fprintf(out, "Dump report for Config [%d,%s]\n", uid, name.c_str());
469 fprintf(out, "See the StatsLogReport in logcat...\n");
470 }
Yao Chen729093d2017-10-16 10:33:26 -0700471 return android::OK;
472 } else {
473 // If arg parsing failed, print the help text and return an error.
474 print_cmd_help(out);
475 return UNKNOWN_ERROR;
476 }
477 } else {
478 fprintf(out, "Log processor does not exist...\n");
479 return UNKNOWN_ERROR;
480 }
481}
482
Yao Chenb3561512017-11-21 18:07:17 -0800483status_t StatsService::cmd_print_stats(FILE* out, const Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800484 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
485 for (const ConfigKey& key : configs) {
486 fprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
487 mProcessor->GetMetricsSize(key));
488 }
David Chenc136f45a2017-11-27 11:52:26 -0800489 fprintf(out, "Detailed statsd stats in logcat...\n");
Yao Chenb3561512017-11-21 18:07:17 -0800490 StatsdStats& statsdStats = StatsdStats::getInstance();
491 bool reset = false;
492 if (args.size() > 1) {
493 reset = strtol(args[1].string(), NULL, 10);
494 }
Yao Chen69f1baf2017-11-27 17:25:36 -0800495 vector<uint8_t> output;
Yao Chenb3561512017-11-21 18:07:17 -0800496 statsdStats.dumpStats(&output, reset);
David Chen1d7b0cd2017-11-15 14:20:04 -0800497 return NO_ERROR;
498}
499
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700500status_t StatsService::cmd_print_uid_map(FILE* out) {
501 mUidMap->printUidMap(out);
502 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700503}
504
yro947fbce2017-11-15 22:50:23 -0800505status_t StatsService::cmd_write_data_to_disk(FILE* out) {
506 fprintf(out, "Writing data to disk\n");
507 mProcessor->WriteDataToDisk();
508 return NO_ERROR;
509}
510
David Chen1481fe12017-10-16 13:16:34 -0700511status_t StatsService::cmd_print_pulled_metrics(FILE* out, const Vector<String8>& args) {
512 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700513 vector<shared_ptr<LogEvent> > stats;
514 if (mStatsPullerManager.Pull(s, &stats)) {
515 for (const auto& it : stats) {
516 fprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
517 }
518 fprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
519 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700520 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700521 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700522}
523
yro74fed972017-11-27 14:42:42 -0800524status_t StatsService::cmd_remove_all_configs(FILE* out) {
525 fprintf(out, "Removing all configs...\n");
526 VLOG("StatsService::cmd_remove_all_configs was called");
527 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800528 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800529 return NO_ERROR;
530}
531
Yao Chen8d9989b2017-11-18 18:54:50 -0800532status_t StatsService::cmd_dump_memory_info(FILE* out) {
533 std::string s = dumpMemInfo(100);
534 fprintf(out, "Memory Info\n");
535 fprintf(out, "%s", s.c_str());
536 return NO_ERROR;
537}
538
Dianne Hackborn3accca02013-09-20 09:32:11 -0700539Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int64_t>& version,
David Chende701692017-10-05 13:16:02 -0700540 const vector<String16>& app) {
yro74fed972017-11-27 14:42:42 -0800541 VLOG("StatsService::informAllUidData was called");
David Chende701692017-10-05 13:16:02 -0700542
543 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
544 return Status::fromExceptionCode(Status::EX_SECURITY,
545 "Only system uid can call informAllUidData");
546 }
547
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700548 mUidMap->updateMap(uid, version, app);
yro74fed972017-11-27 14:42:42 -0800549 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700550
551 return Status::ok();
552}
553
Dianne Hackborn3accca02013-09-20 09:32:11 -0700554Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version) {
yro74fed972017-11-27 14:42:42 -0800555 VLOG("StatsService::informOnePackage was called");
David Chende701692017-10-05 13:16:02 -0700556
557 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
558 return Status::fromExceptionCode(Status::EX_SECURITY,
559 "Only system uid can call informOnePackage");
560 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700561 mUidMap->updateApp(app, uid, version);
David Chende701692017-10-05 13:16:02 -0700562 return Status::ok();
563}
564
565Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
yro74fed972017-11-27 14:42:42 -0800566 VLOG("StatsService::informOnePackageRemoved was called");
David Chende701692017-10-05 13:16:02 -0700567
568 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
569 return Status::fromExceptionCode(Status::EX_SECURITY,
570 "Only system uid can call informOnePackageRemoved");
571 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700572 mUidMap->removeApp(app, uid);
David Chende701692017-10-05 13:16:02 -0700573 return Status::ok();
574}
575
Yao Chenef99c4f2017-09-22 16:26:54 -0700576Status StatsService::informAnomalyAlarmFired() {
yro74fed972017-11-27 14:42:42 -0800577 VLOG("StatsService::informAnomalyAlarmFired was called");
Bookatz1b0b1142017-09-08 11:58:42 -0700578
579 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
580 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700581 "Only system uid can call informAnomalyAlarmFired");
Bookatz1b0b1142017-09-08 11:58:42 -0700582 }
583
yro74fed972017-11-27 14:42:42 -0800584 VLOG("StatsService::informAnomalyAlarmFired succeeded");
Bookatzcc5adef22017-11-21 14:36:23 -0800585 uint64_t currentTimeSec = time(nullptr);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800586 std::unordered_set<sp<const AnomalyAlarm>, SpHash<AnomalyAlarm>> anomalySet =
Bookatzcc5adef22017-11-21 14:36:23 -0800587 mAnomalyMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
588 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, anomalySet);
Bookatz1b0b1142017-09-08 11:58:42 -0700589 return Status::ok();
590}
591
Yao Chenef99c4f2017-09-22 16:26:54 -0700592Status StatsService::informPollAlarmFired() {
yro74fed972017-11-27 14:42:42 -0800593 VLOG("StatsService::informPollAlarmFired was called");
Bookatz1b0b1142017-09-08 11:58:42 -0700594
595 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
596 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700597 "Only system uid can call informPollAlarmFired");
Bookatz1b0b1142017-09-08 11:58:42 -0700598 }
599
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700600 mStatsPullerManager.OnAlarmFired();
Chenjie Yub3dda412017-10-24 13:41:59 -0700601
yro74fed972017-11-27 14:42:42 -0800602 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700603
604 return Status::ok();
605}
606
Yao Chenef99c4f2017-09-22 16:26:54 -0700607Status StatsService::systemRunning() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700608 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
609 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700610 "Only system uid can call systemRunning");
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700611 }
612
613 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800614 VLOG("StatsService::systemRunning");
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700615
Bookatzb487b552017-09-18 11:26:01 -0700616 sayHiToStatsCompanion();
617
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700618 return Status::ok();
619}
620
yro947fbce2017-11-15 22:50:23 -0800621Status StatsService::writeDataToDisk() {
622 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
623 return Status::fromExceptionCode(Status::EX_SECURITY,
624 "Only system uid can call systemRunning");
625 }
626
yro74fed972017-11-27 14:42:42 -0800627 VLOG("StatsService::writeDataToDisk");
yro947fbce2017-11-15 22:50:23 -0800628
629 mProcessor->WriteDataToDisk();
630
631 return Status::ok();
632}
633
Yao Chenef99c4f2017-09-22 16:26:54 -0700634void StatsService::sayHiToStatsCompanion() {
635 // TODO: This method needs to be private. It is temporarily public and unsecured for testing
636 // purposes.
Bookatzb487b552017-09-18 11:26:01 -0700637 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
638 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -0800639 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -0700640 statsCompanion->statsdReady();
641 } else {
yro74fed972017-11-27 14:42:42 -0800642 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -0700643 }
644}
645
Yao Chenef99c4f2017-09-22 16:26:54 -0700646sp<IStatsCompanionService> StatsService::getStatsCompanionService() {
Bookatz906a35c2017-09-20 15:26:44 -0700647 sp<IStatsCompanionService> statsCompanion = nullptr;
648 // Get statscompanion service from service manager
649 const sp<IServiceManager> sm(defaultServiceManager());
650 if (sm != nullptr) {
651 const String16 name("statscompanion");
652 statsCompanion = interface_cast<IStatsCompanionService>(sm->checkService(name));
653 if (statsCompanion == nullptr) {
654 ALOGW("statscompanion service unavailable!");
655 return nullptr;
656 }
657 }
658 return statsCompanion;
659}
660
Yao Chenef99c4f2017-09-22 16:26:54 -0700661Status StatsService::statsCompanionReady() {
yro74fed972017-11-27 14:42:42 -0800662 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -0700663
664 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
665 return Status::fromExceptionCode(Status::EX_SECURITY,
666 "Only system uid can call statsCompanionReady");
667 }
668
669 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
670 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700671 return Status::fromExceptionCode(
672 Status::EX_NULL_POINTER,
673 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700674 }
yro74fed972017-11-27 14:42:42 -0800675 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700676 IInterface::asBinder(statsCompanion)->linkToDeath(new CompanionDeathRecipient(mAnomalyMonitor));
Bookatzb487b552017-09-18 11:26:01 -0700677 mAnomalyMonitor->setStatsCompanionService(statsCompanion);
678
679 return Status::ok();
680}
681
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700682void StatsService::Startup() {
683 mConfigManager->Startup();
Bookatz906a35c2017-09-20 15:26:44 -0700684}
685
Joe Onoratoc4dfae52017-10-17 23:38:21 -0700686void StatsService::OnLogEvent(const LogEvent& event) {
687 mProcessor->OnLogEvent(event);
Bookatz906a35c2017-09-20 15:26:44 -0700688}
689
Yangster7c334a12017-11-22 14:24:24 -0800690Status StatsService::getData(const String16& key, vector<uint8_t>* output) {
David Chenadaf8b32017-11-03 15:42:08 -0700691 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -0800692 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Yao Chen7ee94152017-11-17 09:44:40 -0800693 if (checkCallingPermission(String16(kPermissionDump))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800694 string keyStr = string(String8(key).string());
695 ConfigKey configKey(ipc->getCallingUid(), keyStr);
696 mProcessor->onDumpReport(configKey, output);
David Chenadaf8b32017-11-03 15:42:08 -0700697 return Status::ok();
698 } else {
699 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
700 }
yro31eb67b2017-10-24 13:33:21 -0700701}
702
David Chen2e8f3802017-11-22 10:56:48 -0800703Status StatsService::getMetadata(vector<uint8_t>* output) {
704 IPCThreadState* ipc = IPCThreadState::self();
705 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
706 ipc->getCallingUid());
707 if (checkCallingPermission(String16(kPermissionDump))) {
708 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
709 return Status::ok();
710 } else {
711 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
712 }
713}
714
David Chenadaf8b32017-11-03 15:42:08 -0700715Status StatsService::addConfiguration(const String16& key,
716 const vector <uint8_t>& config,
717 const String16& package, const String16& cls,
718 bool* success) {
719 IPCThreadState* ipc = IPCThreadState::self();
Yao Chen7ee94152017-11-17 09:44:40 -0800720 if (checkCallingPermission(String16(kPermissionDump))) {
David Chenadaf8b32017-11-03 15:42:08 -0700721 string keyString = string(String8(key).string());
David Chen1d7b0cd2017-11-15 14:20:04 -0800722 ConfigKey configKey(ipc->getCallingUid(), keyString);
David Chenadaf8b32017-11-03 15:42:08 -0700723 StatsdConfig cfg;
724 cfg.ParseFromArray(&config[0], config.size());
725 mConfigManager->UpdateConfig(configKey, cfg);
726 mConfigManager->SetConfigReceiver(configKey, string(String8(package).string()),
727 string(String8(cls).string()));
728 *success = true;
729 return Status::ok();
730 } else {
Yao Chenaa39bc72017-12-01 11:16:50 -0800731 *success = false;
David Chenadaf8b32017-11-03 15:42:08 -0700732 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
yro31eb67b2017-10-24 13:33:21 -0700733 }
yro31eb67b2017-10-24 13:33:21 -0700734}
735
David Chenadaf8b32017-11-03 15:42:08 -0700736Status StatsService::removeConfiguration(const String16& key, bool* success) {
737 IPCThreadState* ipc = IPCThreadState::self();
Yao Chen7ee94152017-11-17 09:44:40 -0800738 if (checkCallingPermission(String16(kPermissionDump))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800739 string keyStr = string(String8(key).string());
740 mConfigManager->RemoveConfig(ConfigKey(ipc->getCallingUid(), keyStr));
Yao Chenaa39bc72017-12-01 11:16:50 -0800741 *success = true;
David Chenadaf8b32017-11-03 15:42:08 -0700742 return Status::ok();
743 } else {
744 *success = false;
745 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
yro31eb67b2017-10-24 13:33:21 -0700746 }
yro31eb67b2017-10-24 13:33:21 -0700747}
748
David Chen1d7b0cd2017-11-15 14:20:04 -0800749void StatsService::binderDied(const wp <IBinder>& who) {
yro31eb67b2017-10-24 13:33:21 -0700750}
751
Yao Chenef99c4f2017-09-22 16:26:54 -0700752} // namespace statsd
753} // namespace os
754} // namespace android