blob: aaf1868acbf1e45fd52792407fc7041e7acf15d2 [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"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070025#include "storage/DropboxReader.h"
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070026
David Chen0656b7a2017-09-13 15:53:39 -070027#include <android-base/file.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070028#include <binder/IPCThreadState.h>
29#include <binder/IServiceManager.h>
yro87d983c2017-11-14 21:31:43 -080030#include <dirent.h>
David Chen0656b7a2017-09-13 15:53:39 -070031#include <frameworks/base/cmds/statsd/src/statsd_config.pb.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070032#include <private/android_filesystem_config.h>
33#include <utils/Looper.h>
Joe Onorato2cbc2cc2017-08-30 17:03:23 -070034#include <utils/String16.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070035#include <stdio.h>
Yao Chen482d2722017-09-12 13:25:43 -070036#include <stdlib.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070037#include <sys/system_properties.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070038#include <unistd.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070039
40using namespace android;
41
Bookatz906a35c2017-09-20 15:26:44 -070042namespace android {
43namespace os {
44namespace statsd {
45
David Chenadaf8b32017-11-03 15:42:08 -070046constexpr const char* kPermissionDump = "android.permission.DUMP";
yro87d983c2017-11-14 21:31:43 -080047#define STATS_SERVICE_DIR "/data/system/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070048
Joe Onorato9fc9edf2017-10-15 20:08:52 -070049// ======================================================================
50/**
51 * Watches for the death of the stats companion (system process).
52 */
53class CompanionDeathRecipient : public IBinder::DeathRecipient {
54public:
55 CompanionDeathRecipient(const sp<AnomalyMonitor>& anomalyMonitor);
56 virtual void binderDied(const wp<IBinder>& who);
57
58private:
59 const sp<AnomalyMonitor> mAnomalyMonitor;
60};
61
62CompanionDeathRecipient::CompanionDeathRecipient(const sp<AnomalyMonitor>& anomalyMonitor)
63 : mAnomalyMonitor(anomalyMonitor) {
64}
65
66void CompanionDeathRecipient::binderDied(const wp<IBinder>& who) {
67 ALOGW("statscompanion service died");
68 mAnomalyMonitor->setStatsCompanionService(nullptr);
69}
70
71// ======================================================================
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070072StatsService::StatsService(const sp<Looper>& handlerLooper)
David Chen1481fe12017-10-16 13:16:34 -070073 : mAnomalyMonitor(new AnomalyMonitor(2)) // TODO: Put this comment somewhere better
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070074{
Joe Onorato9fc9edf2017-10-15 20:08:52 -070075 mUidMap = new UidMap();
76 mConfigManager = new ConfigManager();
Yangster-mace2cd6d52017-11-09 20:38:30 -080077 mProcessor = new StatsLogProcessor(mUidMap, mAnomalyMonitor, [this](const ConfigKey& key) {
David Chen1d7b0cd2017-11-15 14:20:04 -080078 auto sc = getStatsCompanionService();
79 auto receiver = mConfigManager->GetConfigReceiver(key);
80 if (sc == nullptr) {
81 ALOGD("Could not find StatsCompanionService");
82 } else if (receiver.first.size() == 0) {
83 ALOGD("Statscompanion could not find a broadcast receiver for %s",
84 key.ToString().c_str());
85 } else {
86 sc->sendBroadcast(String16(receiver.first.c_str()),
87 String16(receiver.second.c_str()));
88 }
yro31eb67b2017-10-24 13:33:21 -070089 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -070090
91 mConfigManager->AddListener(mProcessor);
92
93 init_system_properties();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070094}
95
Yao Chenef99c4f2017-09-22 16:26:54 -070096StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070097}
98
Joe Onorato9fc9edf2017-10-15 20:08:52 -070099void StatsService::init_system_properties() {
100 mEngBuild = false;
101 const prop_info* buildType = __system_property_find("ro.build.type");
102 if (buildType != NULL) {
103 __system_property_read_callback(buildType, init_build_type_callback, this);
104 }
David Chen0656b7a2017-09-13 15:53:39 -0700105}
106
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700107void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
108 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700109 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700110 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
111 }
112}
113
114/**
115 * Implement our own because the default binder implementation isn't
116 * properly handling SHELL_COMMAND_TRANSACTION.
117 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700118status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
119 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700120 status_t err;
121
122 switch (code) {
123 case SHELL_COMMAND_TRANSACTION: {
124 int in = data.readFileDescriptor();
125 int out = data.readFileDescriptor();
126 int err = data.readFileDescriptor();
127 int argc = data.readInt32();
128 Vector<String8> args;
129 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
130 args.add(String8(data.readString16()));
131 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700132 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
133 sp<IResultReceiver> resultReceiver =
134 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700135
136 FILE* fin = fdopen(in, "r");
137 FILE* fout = fdopen(out, "w");
138 FILE* ferr = fdopen(err, "w");
139
140 if (fin == NULL || fout == NULL || ferr == NULL) {
141 resultReceiver->send(NO_MEMORY);
142 } else {
143 err = command(fin, fout, ferr, args);
144 resultReceiver->send(err);
145 }
146
147 if (fin != NULL) {
148 fflush(fin);
149 fclose(fin);
150 }
151 if (fout != NULL) {
152 fflush(fout);
153 fclose(fout);
154 }
155 if (fout != NULL) {
156 fflush(ferr);
157 fclose(ferr);
158 }
159
160 return NO_ERROR;
161 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700162 default: { return BnStatsManager::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700163 }
164}
165
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700166/**
167 * Write debugging data about statsd.
168 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700169status_t StatsService::dump(int fd, const Vector<String16>& args) {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700170 FILE* out = fdopen(fd, "w");
171 if (out == NULL) {
172 return NO_MEMORY; // the fd is already open
173 }
174
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700175 // TODO: Proto format for incident reports
176 dump_impl(out);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700177
178 fclose(out);
179 return NO_ERROR;
180}
181
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700182/**
183 * Write debugging data about statsd in text format.
184 */
185void StatsService::dump_impl(FILE* out) {
186 mConfigManager->Dump(out);
187}
188
189/**
190 * Implementation of the adb shell cmd stats command.
191 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700192status_t StatsService::command(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700193 // TODO: Permission check
194
195 const int argCount = args.size();
196 if (argCount >= 1) {
197 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700198 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700199 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700200 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700201
202 // adb shell cmd stats print-stats-log
203 if (!args[0].compare(String8("print-stats-log")) && args.size() > 1) {
204 return cmd_print_stats_log(out, args);
205 }
206
David Chende701692017-10-05 13:16:02 -0700207 if (!args[0].compare(String8("print-uid-map"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700208 return cmd_print_uid_map(out);
David Chende701692017-10-05 13:16:02 -0700209 }
Yao Chen729093d2017-10-16 10:33:26 -0700210
211 if (!args[0].compare(String8("dump-report"))) {
212 return cmd_dump_report(out, err, args);
213 }
David Chen1481fe12017-10-16 13:16:34 -0700214
215 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
216 return cmd_print_pulled_metrics(out, args);
217 }
David Chenadaf8b32017-11-03 15:42:08 -0700218
219 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800220 return cmd_trigger_broadcast(out, args);
221 }
222
223 if (!args[0].compare(String8("print-stats"))) {
224 return cmd_print_stats(out);
David Chenadaf8b32017-11-03 15:42:08 -0700225 }
yro87d983c2017-11-14 21:31:43 -0800226
227 if (!args[0].compare(String8("clear-config"))) {
228 return cmd_remove_config_files(out);
229 }
Yao Chen8d9989b2017-11-18 18:54:50 -0800230
231 if (!args[0].compare(String8("meminfo"))) {
232 return cmd_dump_memory_info(out);
233 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700234 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700235
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700236 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700237 return NO_ERROR;
238}
239
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700240void StatsService::print_cmd_help(FILE* out) {
241 fprintf(out,
242 "usage: adb shell cmd stats print-stats-log [tag_required] "
243 "[timestamp_nsec_optional]\n");
244 fprintf(out, "\n");
245 fprintf(out, "\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800246 fprintf(out, "usage: adb shell cmd stats meminfo\n");
247 fprintf(out, "\n");
248 fprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
249 fprintf(out, " # adb shell stop\n");
250 fprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
251 fprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
252 fprintf(out, " # adb shell start\n");
253 fprintf(out, "\n");
254 fprintf(out, "\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700255 fprintf(out, "usage: adb shell cmd stats print-uid-map \n");
256 fprintf(out, "\n");
257 fprintf(out, " Prints the UID, app name, version mapping.\n");
258 fprintf(out, "\n");
259 fprintf(out, "\n");
yro87d983c2017-11-14 21:31:43 -0800260 fprintf(out, "usage: adb shell cmd stats clear-config \n");
261 fprintf(out, "\n");
262 fprintf(out, " Removes all configs from disk.\n");
263 fprintf(out, "\n");
264 fprintf(out, "\n");
yro3fca5ba2017-11-17 13:22:52 -0800265 fprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
David Chen1481fe12017-10-16 13:16:34 -0700266 fprintf(out, "\n");
267 fprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
268 fprintf(out, "\n");
269 fprintf(out, "\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700270 fprintf(out, "usage: adb shell cmd stats config remove [UID] NAME\n");
271 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");
274 fprintf(out, " wire-encoded protobuf format and passed via stdin.\n");
275 fprintf(out, "\n");
276 fprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
277 fprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
278 fprintf(out, " uid is used.\n");
279 fprintf(out, " NAME The per-uid name to use\n");
Yao Chen5154a372017-10-30 22:57:06 -0700280 fprintf(out, "\n");
281 fprintf(out, "\n");
282 fprintf(out, "usage: adb shell cmd stats dump-report [UID] NAME\n");
283 fprintf(out, " Dump all metric data for a configuration.\n");
284 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
285 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
286 fprintf(out, " calling uid is used.\n");
287 fprintf(out, " NAME The name of the configuration\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");
298 fprintf(out, "usage: adb shell cmd stats print-stats\n");
299 fprintf(out, " Prints some basic stats.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700300}
301
David Chen1d7b0cd2017-11-15 14:20:04 -0800302status_t StatsService::cmd_trigger_broadcast(FILE* out, Vector<String8>& args) {
303 string name;
304 bool good = false;
305 int uid;
306 const int argCount = args.size();
307 if (argCount == 2) {
308 // Automatically pick the UID
309 uid = IPCThreadState::self()->getCallingUid();
310 // TODO: What if this isn't a binder call? Should we fail?
311 name.assign(args[1].c_str(), args[1].size());
312 good = true;
313 } else if (argCount == 3) {
314 // If it's a userdebug or eng build, then the shell user can
315 // impersonate other uids.
316 if (mEngBuild) {
317 const char* s = args[1].c_str();
318 if (*s != '\0') {
319 char* end = NULL;
320 uid = strtol(s, &end, 0);
321 if (*end == '\0') {
322 name.assign(args[2].c_str(), args[2].size());
323 good = true;
324 }
325 }
326 } else {
327 fprintf(out,
328 "The metrics can only be dumped for other UIDs on eng or userdebug "
329 "builds.\n");
330 }
331 }
332 if (!good) {
333 print_cmd_help(out);
334 return UNKNOWN_ERROR;
335 }
336 auto receiver = mConfigManager->GetConfigReceiver(ConfigKey(uid, name));
yro4d889e62017-11-17 15:44:48 -0800337 sp<IStatsCompanionService> sc = getStatsCompanionService();
338 if (sc != nullptr) {
339 sc->sendBroadcast(String16(receiver.first.c_str()), String16(receiver.second.c_str()));
340 ALOGD("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
341 args[2].c_str());
342 } else {
343 ALOGD("Could not access statsCompanion");
344 }
345
David Chenadaf8b32017-11-03 15:42:08 -0700346 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700347}
348
349status_t StatsService::cmd_config(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
350 const int argCount = args.size();
351 if (argCount >= 2) {
352 if (args[1] == "update" || args[1] == "remove") {
353 bool good = false;
354 int uid = -1;
355 string name;
356
357 if (argCount == 3) {
358 // Automatically pick the UID
359 uid = IPCThreadState::self()->getCallingUid();
360 // TODO: What if this isn't a binder call? Should we fail?
361 name.assign(args[2].c_str(), args[2].size());
362 good = true;
363 } else if (argCount == 4) {
364 // If it's a userdebug or eng build, then the shell user can
365 // impersonate other uids.
366 if (mEngBuild) {
367 const char* s = args[2].c_str();
368 if (*s != '\0') {
369 char* end = NULL;
370 uid = strtol(s, &end, 0);
371 if (*end == '\0') {
372 name.assign(args[3].c_str(), args[3].size());
373 good = true;
374 }
375 }
376 } else {
Yao Chen729093d2017-10-16 10:33:26 -0700377 fprintf(err,
378 "The config can only be set for other UIDs on eng or userdebug "
379 "builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700380 }
381 }
382
383 if (!good) {
384 // If arg parsing failed, print the help text and return an error.
385 print_cmd_help(out);
386 return UNKNOWN_ERROR;
387 }
388
389 if (args[1] == "update") {
390 // Read stream into buffer.
391 string buffer;
392 if (!android::base::ReadFdToString(fileno(in), &buffer)) {
393 fprintf(err, "Error reading stream for StatsConfig.\n");
394 return UNKNOWN_ERROR;
395 }
396
397 // Parse buffer.
398 StatsdConfig config;
399 if (!config.ParseFromString(buffer)) {
400 fprintf(err, "Error parsing proto stream for StatsConfig.\n");
401 return UNKNOWN_ERROR;
402 }
403
404 // Add / update the config.
405 mConfigManager->UpdateConfig(ConfigKey(uid, name), config);
406 } else {
407 // Remove the config.
408 mConfigManager->RemoveConfig(ConfigKey(uid, name));
409 }
410
411 return NO_ERROR;
412 }
David Chen0656b7a2017-09-13 15:53:39 -0700413 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700414 print_cmd_help(out);
415 return UNKNOWN_ERROR;
416}
417
Yao Chen729093d2017-10-16 10:33:26 -0700418status_t StatsService::cmd_dump_report(FILE* out, FILE* err, const Vector<String8>& args) {
419 if (mProcessor != nullptr) {
420 const int argCount = args.size();
421 bool good = false;
422 int uid;
423 string name;
424 if (argCount == 2) {
425 // Automatically pick the UID
426 uid = IPCThreadState::self()->getCallingUid();
427 // TODO: What if this isn't a binder call? Should we fail?
Yao Chen5154a372017-10-30 22:57:06 -0700428 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700429 good = true;
430 } else if (argCount == 3) {
431 // If it's a userdebug or eng build, then the shell user can
432 // impersonate other uids.
433 if (mEngBuild) {
434 const char* s = args[1].c_str();
435 if (*s != '\0') {
436 char* end = NULL;
437 uid = strtol(s, &end, 0);
438 if (*end == '\0') {
439 name.assign(args[2].c_str(), args[2].size());
440 good = true;
441 }
442 }
443 } else {
444 fprintf(out,
445 "The metrics can only be dumped for other UIDs on eng or userdebug "
446 "builds.\n");
447 }
448 }
449 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800450 vector<uint8_t> data;
451 mProcessor->onDumpReport(ConfigKey(uid, name), &data);
Yao Chen729093d2017-10-16 10:33:26 -0700452 // TODO: print the returned StatsLogReport to file instead of printing to logcat.
453 fprintf(out, "Dump report for Config [%d,%s]\n", uid, name.c_str());
454 fprintf(out, "See the StatsLogReport in logcat...\n");
455 return android::OK;
456 } else {
457 // If arg parsing failed, print the help text and return an error.
458 print_cmd_help(out);
459 return UNKNOWN_ERROR;
460 }
461 } else {
462 fprintf(out, "Log processor does not exist...\n");
463 return UNKNOWN_ERROR;
464 }
465}
466
David Chen1d7b0cd2017-11-15 14:20:04 -0800467status_t StatsService::cmd_print_stats(FILE* out) {
468 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
469 for (const ConfigKey& key : configs) {
470 fprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
471 mProcessor->GetMetricsSize(key));
472 }
473 return NO_ERROR;
474}
475
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700476status_t StatsService::cmd_print_stats_log(FILE* out, const Vector<String8>& args) {
477 long msec = 0;
478
479 if (args.size() > 2) {
480 msec = strtol(args[2].string(), NULL, 10);
David Chen0656b7a2017-09-13 15:53:39 -0700481 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700482 return DropboxReader::readStatsLogs(out, args[1].string(), msec);
483}
484
485status_t StatsService::cmd_print_uid_map(FILE* out) {
486 mUidMap->printUidMap(out);
487 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700488}
489
David Chen1481fe12017-10-16 13:16:34 -0700490status_t StatsService::cmd_print_pulled_metrics(FILE* out, const Vector<String8>& args) {
491 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700492 vector<shared_ptr<LogEvent> > stats;
493 if (mStatsPullerManager.Pull(s, &stats)) {
494 for (const auto& it : stats) {
495 fprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
496 }
497 fprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
498 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700499 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700500 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700501}
502
yro87d983c2017-11-14 21:31:43 -0800503status_t StatsService::cmd_remove_config_files(FILE* out) {
504 fprintf(out, "Trying to remove config files...\n");
505 unique_ptr<DIR, decltype(&closedir)> dir(opendir(STATS_SERVICE_DIR), closedir);
506 if (dir == NULL) {
507 fprintf(out, "No existing config files found exiting...\n");
508 return NO_ERROR;
509 }
510
511 dirent* de;
512 while ((de = readdir(dir.get()))) {
513 char* name = de->d_name;
514 if (name[0] == '.') continue;
515 string file_name = StringPrintf("%s/%s", STATS_SERVICE_DIR, name);
516 fprintf(out, "Deleting file %s\n", file_name.c_str());
517 if (remove(file_name.c_str())) {
518 fprintf(out, "Error deleting file %s\n", file_name.c_str());
519 }
520 }
521 return NO_ERROR;
522}
523
Yao Chen8d9989b2017-11-18 18:54:50 -0800524status_t StatsService::cmd_dump_memory_info(FILE* out) {
525 std::string s = dumpMemInfo(100);
526 fprintf(out, "Memory Info\n");
527 fprintf(out, "%s", s.c_str());
528 return NO_ERROR;
529}
530
David Chende701692017-10-05 13:16:02 -0700531Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int32_t>& version,
532 const vector<String16>& app) {
533 if (DEBUG) ALOGD("StatsService::informAllUidData was called");
534
535 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
536 return Status::fromExceptionCode(Status::EX_SECURITY,
537 "Only system uid can call informAllUidData");
538 }
539
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700540 mUidMap->updateMap(uid, version, app);
David Chende701692017-10-05 13:16:02 -0700541 if (DEBUG) ALOGD("StatsService::informAllUidData succeeded");
542
543 return Status::ok();
544}
545
546Status StatsService::informOnePackage(const String16& app, int32_t uid, int32_t version) {
547 if (DEBUG) ALOGD("StatsService::informOnePackage was called");
548
549 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
550 return Status::fromExceptionCode(Status::EX_SECURITY,
551 "Only system uid can call informOnePackage");
552 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700553 mUidMap->updateApp(app, uid, version);
David Chende701692017-10-05 13:16:02 -0700554 return Status::ok();
555}
556
557Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
558 if (DEBUG) ALOGD("StatsService::informOnePackageRemoved was called");
559
560 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
561 return Status::fromExceptionCode(Status::EX_SECURITY,
562 "Only system uid can call informOnePackageRemoved");
563 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700564 mUidMap->removeApp(app, uid);
David Chende701692017-10-05 13:16:02 -0700565 return Status::ok();
566}
567
Yao Chenef99c4f2017-09-22 16:26:54 -0700568Status StatsService::informAnomalyAlarmFired() {
Bookatzb487b552017-09-18 11:26:01 -0700569 if (DEBUG) ALOGD("StatsService::informAnomalyAlarmFired was called");
Bookatz1b0b1142017-09-08 11:58:42 -0700570
571 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
572 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700573 "Only system uid can call informAnomalyAlarmFired");
Bookatz1b0b1142017-09-08 11:58:42 -0700574 }
575
Bookatzb487b552017-09-18 11:26:01 -0700576 if (DEBUG) ALOGD("StatsService::informAnomalyAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700577 // TODO: check through all counters/timers and see if an anomaly has indeed occurred.
Yangster-mace2cd6d52017-11-09 20:38:30 -0800578 uint64_t currentTimeNs = time(nullptr) * NS_PER_SEC;
579 std::unordered_set<sp<const AnomalyAlarm>, SpHash<AnomalyAlarm>> anomalySet =
580 mAnomalyMonitor->onAlarmFired(currentTimeNs);
581 mProcessor->onAnomalyAlarmFired(currentTimeNs, anomalySet);
Bookatz1b0b1142017-09-08 11:58:42 -0700582 return Status::ok();
583}
584
Yao Chenef99c4f2017-09-22 16:26:54 -0700585Status StatsService::informPollAlarmFired() {
Bookatzb487b552017-09-18 11:26:01 -0700586 if (DEBUG) ALOGD("StatsService::informPollAlarmFired was called");
Bookatz1b0b1142017-09-08 11:58:42 -0700587
588 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
589 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700590 "Only system uid can call informPollAlarmFired");
Bookatz1b0b1142017-09-08 11:58:42 -0700591 }
592
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700593 mStatsPullerManager.OnAlarmFired();
Chenjie Yub3dda412017-10-24 13:41:59 -0700594
Bookatzb487b552017-09-18 11:26:01 -0700595 if (DEBUG) ALOGD("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700596
597 return Status::ok();
598}
599
Yao Chenef99c4f2017-09-22 16:26:54 -0700600Status StatsService::systemRunning() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700601 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
602 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700603 "Only system uid can call systemRunning");
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700604 }
605
606 // When system_server is up and running, schedule the dropbox task to run.
607 ALOGD("StatsService::systemRunning");
608
Bookatzb487b552017-09-18 11:26:01 -0700609 sayHiToStatsCompanion();
610
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700611 return Status::ok();
612}
613
Yao Chenef99c4f2017-09-22 16:26:54 -0700614void StatsService::sayHiToStatsCompanion() {
615 // TODO: This method needs to be private. It is temporarily public and unsecured for testing
616 // purposes.
Bookatzb487b552017-09-18 11:26:01 -0700617 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
618 if (statsCompanion != nullptr) {
619 if (DEBUG) ALOGD("Telling statsCompanion that statsd is ready");
620 statsCompanion->statsdReady();
621 } else {
622 if (DEBUG) ALOGD("Could not access statsCompanion");
623 }
624}
625
Yao Chenef99c4f2017-09-22 16:26:54 -0700626sp<IStatsCompanionService> StatsService::getStatsCompanionService() {
Bookatz906a35c2017-09-20 15:26:44 -0700627 sp<IStatsCompanionService> statsCompanion = nullptr;
628 // Get statscompanion service from service manager
629 const sp<IServiceManager> sm(defaultServiceManager());
630 if (sm != nullptr) {
631 const String16 name("statscompanion");
632 statsCompanion = interface_cast<IStatsCompanionService>(sm->checkService(name));
633 if (statsCompanion == nullptr) {
634 ALOGW("statscompanion service unavailable!");
635 return nullptr;
636 }
637 }
638 return statsCompanion;
639}
640
Yao Chenef99c4f2017-09-22 16:26:54 -0700641Status StatsService::statsCompanionReady() {
Bookatzb487b552017-09-18 11:26:01 -0700642 if (DEBUG) ALOGD("StatsService::statsCompanionReady was called");
643
644 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
645 return Status::fromExceptionCode(Status::EX_SECURITY,
646 "Only system uid can call statsCompanionReady");
647 }
648
649 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
650 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700651 return Status::fromExceptionCode(
652 Status::EX_NULL_POINTER,
653 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700654 }
655 if (DEBUG) ALOGD("StatsService::statsCompanionReady linking to statsCompanion.");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700656 IInterface::asBinder(statsCompanion)->linkToDeath(new CompanionDeathRecipient(mAnomalyMonitor));
Bookatzb487b552017-09-18 11:26:01 -0700657 mAnomalyMonitor->setStatsCompanionService(statsCompanion);
658
659 return Status::ok();
660}
661
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700662void StatsService::Startup() {
663 mConfigManager->Startup();
Bookatz906a35c2017-09-20 15:26:44 -0700664}
665
Joe Onoratoc4dfae52017-10-17 23:38:21 -0700666void StatsService::OnLogEvent(const LogEvent& event) {
667 mProcessor->OnLogEvent(event);
Bookatz906a35c2017-09-20 15:26:44 -0700668}
669
Yangster7c334a12017-11-22 14:24:24 -0800670Status StatsService::getData(const String16& key, vector<uint8_t>* output) {
David Chenadaf8b32017-11-03 15:42:08 -0700671 IPCThreadState* ipc = IPCThreadState::self();
David Chen1d7b0cd2017-11-15 14:20:04 -0800672 ALOGD("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(),
673 ipc->getCallingUid());
Yao Chen7ee94152017-11-17 09:44:40 -0800674 if (checkCallingPermission(String16(kPermissionDump))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800675 string keyStr = string(String8(key).string());
676 ConfigKey configKey(ipc->getCallingUid(), keyStr);
677 mProcessor->onDumpReport(configKey, output);
David Chenadaf8b32017-11-03 15:42:08 -0700678 return Status::ok();
679 } else {
680 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
681 }
yro31eb67b2017-10-24 13:33:21 -0700682}
683
David Chenadaf8b32017-11-03 15:42:08 -0700684Status StatsService::addConfiguration(const String16& key,
685 const vector <uint8_t>& config,
686 const String16& package, const String16& cls,
687 bool* success) {
688 IPCThreadState* ipc = IPCThreadState::self();
Yao Chen7ee94152017-11-17 09:44:40 -0800689 if (checkCallingPermission(String16(kPermissionDump))) {
David Chenadaf8b32017-11-03 15:42:08 -0700690 string keyString = string(String8(key).string());
David Chen1d7b0cd2017-11-15 14:20:04 -0800691 ConfigKey configKey(ipc->getCallingUid(), keyString);
David Chenadaf8b32017-11-03 15:42:08 -0700692 StatsdConfig cfg;
693 cfg.ParseFromArray(&config[0], config.size());
694 mConfigManager->UpdateConfig(configKey, cfg);
695 mConfigManager->SetConfigReceiver(configKey, string(String8(package).string()),
696 string(String8(cls).string()));
697 *success = true;
698 return Status::ok();
699 } else {
700 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
yro31eb67b2017-10-24 13:33:21 -0700701 }
yro31eb67b2017-10-24 13:33:21 -0700702}
703
David Chenadaf8b32017-11-03 15:42:08 -0700704Status StatsService::removeConfiguration(const String16& key, bool* success) {
705 IPCThreadState* ipc = IPCThreadState::self();
Yao Chen7ee94152017-11-17 09:44:40 -0800706 if (checkCallingPermission(String16(kPermissionDump))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800707 string keyStr = string(String8(key).string());
708 mConfigManager->RemoveConfig(ConfigKey(ipc->getCallingUid(), keyStr));
David Chenadaf8b32017-11-03 15:42:08 -0700709 return Status::ok();
710 } else {
711 *success = false;
712 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
yro31eb67b2017-10-24 13:33:21 -0700713 }
yro31eb67b2017-10-24 13:33:21 -0700714}
715
David Chen1d7b0cd2017-11-15 14:20:04 -0800716void StatsService::binderDied(const wp <IBinder>& who) {
yro31eb67b2017-10-24 13:33:21 -0700717}
718
Yao Chenef99c4f2017-09-22 16:26:54 -0700719} // namespace statsd
720} // namespace os
721} // namespace android