blob: 0e9cd3b2a14818d85cf9388d4743869dc9eaf99a [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"
Joe Onorato9fc9edf2017-10-15 20:08:52 -070026#include "storage/DropboxReader.h"
yro947fbce2017-11-15 22:50:23 -080027#include "storage/StorageManager.h"
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070028
David Chen0656b7a2017-09-13 15:53:39 -070029#include <android-base/file.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070030#include <binder/IPCThreadState.h>
31#include <binder/IServiceManager.h>
yro87d983c2017-11-14 21:31:43 -080032#include <dirent.h>
David Chen0656b7a2017-09-13 15:53:39 -070033#include <frameworks/base/cmds/statsd/src/statsd_config.pb.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070034#include <private/android_filesystem_config.h>
35#include <utils/Looper.h>
Joe Onorato2cbc2cc2017-08-30 17:03:23 -070036#include <utils/String16.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070037#include <stdio.h>
Yao Chen482d2722017-09-12 13:25:43 -070038#include <stdlib.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070039#include <sys/system_properties.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070040#include <unistd.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070041
42using namespace android;
43
Bookatz906a35c2017-09-20 15:26:44 -070044namespace android {
45namespace os {
46namespace statsd {
47
David Chenadaf8b32017-11-03 15:42:08 -070048constexpr const char* kPermissionDump = "android.permission.DUMP";
yro87d983c2017-11-14 21:31:43 -080049#define STATS_SERVICE_DIR "/data/system/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070050
Joe Onorato9fc9edf2017-10-15 20:08:52 -070051// ======================================================================
52/**
53 * Watches for the death of the stats companion (system process).
54 */
55class CompanionDeathRecipient : public IBinder::DeathRecipient {
56public:
57 CompanionDeathRecipient(const sp<AnomalyMonitor>& anomalyMonitor);
58 virtual void binderDied(const wp<IBinder>& who);
59
60private:
61 const sp<AnomalyMonitor> mAnomalyMonitor;
62};
63
64CompanionDeathRecipient::CompanionDeathRecipient(const sp<AnomalyMonitor>& anomalyMonitor)
65 : mAnomalyMonitor(anomalyMonitor) {
66}
67
68void CompanionDeathRecipient::binderDied(const wp<IBinder>& who) {
69 ALOGW("statscompanion service died");
70 mAnomalyMonitor->setStatsCompanionService(nullptr);
71}
72
73// ======================================================================
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070074StatsService::StatsService(const sp<Looper>& handlerLooper)
David Chen1481fe12017-10-16 13:16:34 -070075 : mAnomalyMonitor(new AnomalyMonitor(2)) // TODO: Put this comment somewhere better
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070076{
Joe Onorato9fc9edf2017-10-15 20:08:52 -070077 mUidMap = new UidMap();
78 mConfigManager = new ConfigManager();
Yangster-mace2cd6d52017-11-09 20:38:30 -080079 mProcessor = new StatsLogProcessor(mUidMap, mAnomalyMonitor, [this](const ConfigKey& key) {
yro947fbce2017-11-15 22:50:23 -080080 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen1d7b0cd2017-11-15 14:20:04 -080081 auto receiver = mConfigManager->GetConfigReceiver(key);
82 if (sc == nullptr) {
yro74fed972017-11-27 14:42:42 -080083 VLOG("Could not find StatsCompanionService");
David Chen1d7b0cd2017-11-15 14:20:04 -080084 } else if (receiver.first.size() == 0) {
yro74fed972017-11-27 14:42:42 -080085 VLOG("Statscompanion could not find a broadcast receiver for %s",
86 key.ToString().c_str());
David Chen1d7b0cd2017-11-15 14:20:04 -080087 } else {
88 sc->sendBroadcast(String16(receiver.first.c_str()),
89 String16(receiver.second.c_str()));
90 }
yro31eb67b2017-10-24 13:33:21 -070091 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -070092
93 mConfigManager->AddListener(mProcessor);
94
95 init_system_properties();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070096}
97
Yao Chenef99c4f2017-09-22 16:26:54 -070098StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070099}
100
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700101void StatsService::init_system_properties() {
102 mEngBuild = false;
103 const prop_info* buildType = __system_property_find("ro.build.type");
104 if (buildType != NULL) {
105 __system_property_read_callback(buildType, init_build_type_callback, this);
106 }
David Chen0656b7a2017-09-13 15:53:39 -0700107}
108
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700109void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
110 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700111 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700112 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
113 }
114}
115
116/**
117 * Implement our own because the default binder implementation isn't
118 * properly handling SHELL_COMMAND_TRANSACTION.
119 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700120status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
121 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700122 status_t err;
123
124 switch (code) {
125 case SHELL_COMMAND_TRANSACTION: {
126 int in = data.readFileDescriptor();
127 int out = data.readFileDescriptor();
128 int err = data.readFileDescriptor();
129 int argc = data.readInt32();
130 Vector<String8> args;
131 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
132 args.add(String8(data.readString16()));
133 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700134 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
135 sp<IResultReceiver> resultReceiver =
136 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700137
138 FILE* fin = fdopen(in, "r");
139 FILE* fout = fdopen(out, "w");
140 FILE* ferr = fdopen(err, "w");
141
142 if (fin == NULL || fout == NULL || ferr == NULL) {
143 resultReceiver->send(NO_MEMORY);
144 } else {
145 err = command(fin, fout, ferr, args);
146 resultReceiver->send(err);
147 }
148
149 if (fin != NULL) {
150 fflush(fin);
151 fclose(fin);
152 }
153 if (fout != NULL) {
154 fflush(fout);
155 fclose(fout);
156 }
157 if (fout != NULL) {
158 fflush(ferr);
159 fclose(ferr);
160 }
161
162 return NO_ERROR;
163 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700164 default: { return BnStatsManager::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700165 }
166}
167
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700168/**
169 * Write debugging data about statsd.
170 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700171status_t StatsService::dump(int fd, const Vector<String16>& args) {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700172 FILE* out = fdopen(fd, "w");
173 if (out == NULL) {
174 return NO_MEMORY; // the fd is already open
175 }
176
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700177 // TODO: Proto format for incident reports
178 dump_impl(out);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700179
180 fclose(out);
181 return NO_ERROR;
182}
183
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700184/**
185 * Write debugging data about statsd in text format.
186 */
187void StatsService::dump_impl(FILE* out) {
188 mConfigManager->Dump(out);
189}
190
191/**
192 * Implementation of the adb shell cmd stats command.
193 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700194status_t StatsService::command(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700195 // TODO: Permission check
196
197 const int argCount = args.size();
198 if (argCount >= 1) {
199 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700200 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700201 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700202 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700203
204 // adb shell cmd stats print-stats-log
205 if (!args[0].compare(String8("print-stats-log")) && args.size() > 1) {
206 return cmd_print_stats_log(out, args);
207 }
208
David Chende701692017-10-05 13:16:02 -0700209 if (!args[0].compare(String8("print-uid-map"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700210 return cmd_print_uid_map(out);
David Chende701692017-10-05 13:16:02 -0700211 }
Yao Chen729093d2017-10-16 10:33:26 -0700212
213 if (!args[0].compare(String8("dump-report"))) {
214 return cmd_dump_report(out, err, args);
215 }
David Chen1481fe12017-10-16 13:16:34 -0700216
217 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
218 return cmd_print_pulled_metrics(out, args);
219 }
David Chenadaf8b32017-11-03 15:42:08 -0700220
221 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800222 return cmd_trigger_broadcast(out, args);
223 }
224
225 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800226 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700227 }
yro87d983c2017-11-14 21:31:43 -0800228
Yao Chen8d9989b2017-11-18 18:54:50 -0800229 if (!args[0].compare(String8("meminfo"))) {
230 return cmd_dump_memory_info(out);
231 }
yro947fbce2017-11-15 22:50:23 -0800232
233 if (!args[0].compare(String8("write-to-disk"))) {
234 return cmd_write_data_to_disk(out);
235 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700236 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700237
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700238 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700239 return NO_ERROR;
240}
241
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700242void StatsService::print_cmd_help(FILE* out) {
243 fprintf(out,
244 "usage: adb shell cmd stats print-stats-log [tag_required] "
245 "[timestamp_nsec_optional]\n");
246 fprintf(out, "\n");
247 fprintf(out, "\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800248 fprintf(out, "usage: adb shell cmd stats meminfo\n");
249 fprintf(out, "\n");
250 fprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
251 fprintf(out, " # adb shell stop\n");
252 fprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
253 fprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
254 fprintf(out, " # adb shell start\n");
255 fprintf(out, "\n");
256 fprintf(out, "\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700257 fprintf(out, "usage: adb shell cmd stats print-uid-map \n");
258 fprintf(out, "\n");
259 fprintf(out, " Prints the UID, app name, version mapping.\n");
260 fprintf(out, "\n");
261 fprintf(out, "\n");
yro3fca5ba2017-11-17 13:22:52 -0800262 fprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
David Chen1481fe12017-10-16 13:16:34 -0700263 fprintf(out, "\n");
264 fprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
265 fprintf(out, "\n");
266 fprintf(out, "\n");
yro947fbce2017-11-15 22:50:23 -0800267 fprintf(out, "usage: adb shell cmd stats write-to-disk \n");
268 fprintf(out, "\n");
269 fprintf(out, " Flushes all data on memory to disk.\n");
270 fprintf(out, "\n");
271 fprintf(out, "\n");
yro74fed972017-11-27 14:42:42 -0800272 fprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700273 fprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
274 fprintf(out, "\n");
275 fprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
yro74fed972017-11-27 14:42:42 -0800276 fprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
277 fprintf(out, " provided, then all configs will be removed from memory and disk.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700278 fprintf(out, "\n");
279 fprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
yro74fed972017-11-27 14:42:42 -0800280 fprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700281 fprintf(out, " uid is used.\n");
282 fprintf(out, " NAME The per-uid name to use\n");
Yao Chen5154a372017-10-30 22:57:06 -0700283 fprintf(out, "\n");
yro74fed972017-11-27 14:42:42 -0800284 fprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
285 fprintf(out, "\n be removed from memory and disk!\n");
Yao Chen5154a372017-10-30 22:57:06 -0700286 fprintf(out, "\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800287 fprintf(out, "usage: adb shell cmd stats dump-report [UID] NAME [--proto]\n");
Yao Chen5154a372017-10-30 22:57:06 -0700288 fprintf(out, " Dump all metric data for a configuration.\n");
289 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
290 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
291 fprintf(out, " calling uid is used.\n");
292 fprintf(out, " NAME The name of the configuration\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800293 fprintf(out, " --proto Print proto binary.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700294 fprintf(out, "\n");
295 fprintf(out, "\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800296 fprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
297 fprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
298 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
299 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
300 fprintf(out, " calling uid is used.\n");
301 fprintf(out, " NAME The name of the configuration\n");
302 fprintf(out, "\n");
303 fprintf(out, "\n");
Yao Chenb3561512017-11-21 18:07:17 -0800304 fprintf(out, "usage: adb shell cmd stats print-stats [reset]\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800305 fprintf(out, " Prints some basic stats.\n");
Yao Chenb3561512017-11-21 18:07:17 -0800306 fprintf(out, " reset: 1 to reset the statsd stats. default=0.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700307}
308
David Chen1d7b0cd2017-11-15 14:20:04 -0800309status_t StatsService::cmd_trigger_broadcast(FILE* out, Vector<String8>& args) {
310 string name;
311 bool good = false;
312 int uid;
313 const int argCount = args.size();
314 if (argCount == 2) {
315 // Automatically pick the UID
316 uid = IPCThreadState::self()->getCallingUid();
317 // TODO: What if this isn't a binder call? Should we fail?
318 name.assign(args[1].c_str(), args[1].size());
319 good = true;
320 } else if (argCount == 3) {
321 // If it's a userdebug or eng build, then the shell user can
322 // impersonate other uids.
323 if (mEngBuild) {
324 const char* s = args[1].c_str();
325 if (*s != '\0') {
326 char* end = NULL;
327 uid = strtol(s, &end, 0);
328 if (*end == '\0') {
329 name.assign(args[2].c_str(), args[2].size());
330 good = true;
331 }
332 }
333 } else {
334 fprintf(out,
335 "The metrics can only be dumped for other UIDs on eng or userdebug "
336 "builds.\n");
337 }
338 }
339 if (!good) {
340 print_cmd_help(out);
341 return UNKNOWN_ERROR;
342 }
343 auto receiver = mConfigManager->GetConfigReceiver(ConfigKey(uid, name));
yro4d889e62017-11-17 15:44:48 -0800344 sp<IStatsCompanionService> sc = getStatsCompanionService();
345 if (sc != nullptr) {
346 sc->sendBroadcast(String16(receiver.first.c_str()), String16(receiver.second.c_str()));
yro74fed972017-11-27 14:42:42 -0800347 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
348 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800349 } else {
yro74fed972017-11-27 14:42:42 -0800350 VLOG("Could not access statsCompanion");
yro4d889e62017-11-17 15:44:48 -0800351 }
352
David Chenadaf8b32017-11-03 15:42:08 -0700353 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700354}
355
356status_t StatsService::cmd_config(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
357 const int argCount = args.size();
358 if (argCount >= 2) {
359 if (args[1] == "update" || args[1] == "remove") {
360 bool good = false;
361 int uid = -1;
362 string name;
363
364 if (argCount == 3) {
365 // Automatically pick the UID
366 uid = IPCThreadState::self()->getCallingUid();
367 // TODO: What if this isn't a binder call? Should we fail?
368 name.assign(args[2].c_str(), args[2].size());
369 good = true;
370 } else if (argCount == 4) {
371 // If it's a userdebug or eng build, then the shell user can
372 // impersonate other uids.
373 if (mEngBuild) {
374 const char* s = args[2].c_str();
375 if (*s != '\0') {
376 char* end = NULL;
377 uid = strtol(s, &end, 0);
378 if (*end == '\0') {
379 name.assign(args[3].c_str(), args[3].size());
380 good = true;
381 }
382 }
383 } else {
Yao Chen729093d2017-10-16 10:33:26 -0700384 fprintf(err,
385 "The config can only be set for other UIDs on eng or userdebug "
386 "builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700387 }
388 }
389
390 if (!good) {
391 // If arg parsing failed, print the help text and return an error.
392 print_cmd_help(out);
393 return UNKNOWN_ERROR;
394 }
395
396 if (args[1] == "update") {
397 // Read stream into buffer.
398 string buffer;
399 if (!android::base::ReadFdToString(fileno(in), &buffer)) {
400 fprintf(err, "Error reading stream for StatsConfig.\n");
401 return UNKNOWN_ERROR;
402 }
403
404 // Parse buffer.
405 StatsdConfig config;
406 if (!config.ParseFromString(buffer)) {
407 fprintf(err, "Error parsing proto stream for StatsConfig.\n");
408 return UNKNOWN_ERROR;
409 }
410
411 // Add / update the config.
412 mConfigManager->UpdateConfig(ConfigKey(uid, name), config);
413 } else {
yro74fed972017-11-27 14:42:42 -0800414 if (argCount == 2) {
415 cmd_remove_all_configs(out);
416 } else {
417 // Remove the config.
418 mConfigManager->RemoveConfig(ConfigKey(uid, name));
419 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700420 }
421
422 return NO_ERROR;
423 }
David Chen0656b7a2017-09-13 15:53:39 -0700424 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700425 print_cmd_help(out);
426 return UNKNOWN_ERROR;
427}
428
Yao Chen729093d2017-10-16 10:33:26 -0700429status_t StatsService::cmd_dump_report(FILE* out, FILE* err, const Vector<String8>& args) {
430 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800431 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700432 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800433 bool proto = false;
Yao Chen729093d2017-10-16 10:33:26 -0700434 int uid;
435 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800436 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
437 proto = true;
438 argCount -= 1;
439 }
Yao Chen729093d2017-10-16 10:33:26 -0700440 if (argCount == 2) {
441 // Automatically pick the UID
442 uid = IPCThreadState::self()->getCallingUid();
443 // TODO: What if this isn't a binder call? Should we fail?
Yao Chen5154a372017-10-30 22:57:06 -0700444 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700445 good = true;
446 } else if (argCount == 3) {
447 // If it's a userdebug or eng build, then the shell user can
448 // impersonate other uids.
449 if (mEngBuild) {
450 const char* s = args[1].c_str();
451 if (*s != '\0') {
452 char* end = NULL;
453 uid = strtol(s, &end, 0);
454 if (*end == '\0') {
455 name.assign(args[2].c_str(), args[2].size());
456 good = true;
457 }
458 }
459 } else {
460 fprintf(out,
461 "The metrics can only be dumped for other UIDs on eng or userdebug "
462 "builds.\n");
463 }
464 }
465 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800466 vector<uint8_t> data;
467 mProcessor->onDumpReport(ConfigKey(uid, name), &data);
Yao Chen729093d2017-10-16 10:33:26 -0700468 // TODO: print the returned StatsLogReport to file instead of printing to logcat.
Chenjie Yub236c862017-11-28 22:20:44 -0800469 if (proto) {
470 for (size_t i = 0; i < data.size(); i ++) {
471 fprintf(out, "%c", data[i]);
472 }
473 } else {
474 fprintf(out, "Dump report for Config [%d,%s]\n", uid, name.c_str());
475 fprintf(out, "See the StatsLogReport in logcat...\n");
476 }
Yao Chen729093d2017-10-16 10:33:26 -0700477 return android::OK;
478 } else {
479 // If arg parsing failed, print the help text and return an error.
480 print_cmd_help(out);
481 return UNKNOWN_ERROR;
482 }
483 } else {
484 fprintf(out, "Log processor does not exist...\n");
485 return UNKNOWN_ERROR;
486 }
487}
488
Yao Chenb3561512017-11-21 18:07:17 -0800489status_t StatsService::cmd_print_stats(FILE* out, const Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800490 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
491 for (const ConfigKey& key : configs) {
492 fprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
493 mProcessor->GetMetricsSize(key));
494 }
David Chenc136f452017-11-27 11:52:26 -0800495 fprintf(out, "Detailed statsd stats in logcat...\n");
Yao Chenb3561512017-11-21 18:07:17 -0800496 StatsdStats& statsdStats = StatsdStats::getInstance();
497 bool reset = false;
498 if (args.size() > 1) {
499 reset = strtol(args[1].string(), NULL, 10);
500 }
Yao Chen69f1baf2017-11-27 17:25:36 -0800501 vector<uint8_t> output;
Yao Chenb3561512017-11-21 18:07:17 -0800502 statsdStats.dumpStats(&output, reset);
David Chen1d7b0cd2017-11-15 14:20:04 -0800503 return NO_ERROR;
504}
505
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700506status_t StatsService::cmd_print_stats_log(FILE* out, const Vector<String8>& args) {
507 long msec = 0;
508
509 if (args.size() > 2) {
510 msec = strtol(args[2].string(), NULL, 10);
David Chen0656b7a2017-09-13 15:53:39 -0700511 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700512 return DropboxReader::readStatsLogs(out, args[1].string(), msec);
513}
514
515status_t StatsService::cmd_print_uid_map(FILE* out) {
516 mUidMap->printUidMap(out);
517 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700518}
519
yro947fbce2017-11-15 22:50:23 -0800520status_t StatsService::cmd_write_data_to_disk(FILE* out) {
521 fprintf(out, "Writing data to disk\n");
522 mProcessor->WriteDataToDisk();
523 return NO_ERROR;
524}
525
David Chen1481fe12017-10-16 13:16:34 -0700526status_t StatsService::cmd_print_pulled_metrics(FILE* out, const Vector<String8>& args) {
527 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700528 vector<shared_ptr<LogEvent> > stats;
529 if (mStatsPullerManager.Pull(s, &stats)) {
530 for (const auto& it : stats) {
531 fprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
532 }
533 fprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
534 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700535 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700536 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700537}
538
yro74fed972017-11-27 14:42:42 -0800539status_t StatsService::cmd_remove_all_configs(FILE* out) {
540 fprintf(out, "Removing all configs...\n");
541 VLOG("StatsService::cmd_remove_all_configs was called");
542 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800543 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800544 return NO_ERROR;
545}
546
Yao Chen8d9989b2017-11-18 18:54:50 -0800547status_t StatsService::cmd_dump_memory_info(FILE* out) {
548 std::string s = dumpMemInfo(100);
549 fprintf(out, "Memory Info\n");
550 fprintf(out, "%s", s.c_str());
551 return NO_ERROR;
552}
553
David Chende701692017-10-05 13:16:02 -0700554Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int32_t>& version,
555 const vector<String16>& app) {
yro74fed972017-11-27 14:42:42 -0800556 VLOG("StatsService::informAllUidData was called");
David Chende701692017-10-05 13:16:02 -0700557
558 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
559 return Status::fromExceptionCode(Status::EX_SECURITY,
560 "Only system uid can call informAllUidData");
561 }
562
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700563 mUidMap->updateMap(uid, version, app);
yro74fed972017-11-27 14:42:42 -0800564 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700565
566 return Status::ok();
567}
568
569Status StatsService::informOnePackage(const String16& app, int32_t uid, int32_t version) {
yro74fed972017-11-27 14:42:42 -0800570 VLOG("StatsService::informOnePackage was called");
David Chende701692017-10-05 13:16:02 -0700571
572 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
573 return Status::fromExceptionCode(Status::EX_SECURITY,
574 "Only system uid can call informOnePackage");
575 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700576 mUidMap->updateApp(app, uid, version);
David Chende701692017-10-05 13:16:02 -0700577 return Status::ok();
578}
579
580Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
yro74fed972017-11-27 14:42:42 -0800581 VLOG("StatsService::informOnePackageRemoved was called");
David Chende701692017-10-05 13:16:02 -0700582
583 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
584 return Status::fromExceptionCode(Status::EX_SECURITY,
585 "Only system uid can call informOnePackageRemoved");
586 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700587 mUidMap->removeApp(app, uid);
David Chende701692017-10-05 13:16:02 -0700588 return Status::ok();
589}
590
Yao Chenef99c4f2017-09-22 16:26:54 -0700591Status StatsService::informAnomalyAlarmFired() {
yro74fed972017-11-27 14:42:42 -0800592 VLOG("StatsService::informAnomalyAlarmFired was called");
Bookatz1b0b1142017-09-08 11:58:42 -0700593
594 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
595 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700596 "Only system uid can call informAnomalyAlarmFired");
Bookatz1b0b1142017-09-08 11:58:42 -0700597 }
598
yro74fed972017-11-27 14:42:42 -0800599 VLOG("StatsService::informAnomalyAlarmFired succeeded");
Bookatzcc5adef2017-11-21 14:36:23 -0800600 uint64_t currentTimeSec = time(nullptr);
Yangster-mace2cd6d52017-11-09 20:38:30 -0800601 std::unordered_set<sp<const AnomalyAlarm>, SpHash<AnomalyAlarm>> anomalySet =
Bookatzcc5adef2017-11-21 14:36:23 -0800602 mAnomalyMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
603 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, anomalySet);
Bookatz1b0b1142017-09-08 11:58:42 -0700604 return Status::ok();
605}
606
Yao Chenef99c4f2017-09-22 16:26:54 -0700607Status StatsService::informPollAlarmFired() {
yro74fed972017-11-27 14:42:42 -0800608 VLOG("StatsService::informPollAlarmFired was called");
Bookatz1b0b1142017-09-08 11:58:42 -0700609
610 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
611 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700612 "Only system uid can call informPollAlarmFired");
Bookatz1b0b1142017-09-08 11:58:42 -0700613 }
614
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700615 mStatsPullerManager.OnAlarmFired();
Chenjie Yub3dda412017-10-24 13:41:59 -0700616
yro74fed972017-11-27 14:42:42 -0800617 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700618
619 return Status::ok();
620}
621
Yao Chenef99c4f2017-09-22 16:26:54 -0700622Status StatsService::systemRunning() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700623 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
624 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700625 "Only system uid can call systemRunning");
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700626 }
627
628 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800629 VLOG("StatsService::systemRunning");
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700630
Bookatzb487b552017-09-18 11:26:01 -0700631 sayHiToStatsCompanion();
632
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700633 return Status::ok();
634}
635
yro947fbce2017-11-15 22:50:23 -0800636Status StatsService::writeDataToDisk() {
637 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
638 return Status::fromExceptionCode(Status::EX_SECURITY,
639 "Only system uid can call systemRunning");
640 }
641
yro74fed972017-11-27 14:42:42 -0800642 VLOG("StatsService::writeDataToDisk");
yro947fbce2017-11-15 22:50:23 -0800643
644 mProcessor->WriteDataToDisk();
645
646 return Status::ok();
647}
648
Yao Chenef99c4f2017-09-22 16:26:54 -0700649void StatsService::sayHiToStatsCompanion() {
650 // TODO: This method needs to be private. It is temporarily public and unsecured for testing
651 // purposes.
Bookatzb487b552017-09-18 11:26:01 -0700652 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
653 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -0800654 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -0700655 statsCompanion->statsdReady();
656 } else {
yro74fed972017-11-27 14:42:42 -0800657 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -0700658 }
659}
660
Yao Chenef99c4f2017-09-22 16:26:54 -0700661sp<IStatsCompanionService> StatsService::getStatsCompanionService() {
Bookatz906a35c2017-09-20 15:26:44 -0700662 sp<IStatsCompanionService> statsCompanion = nullptr;
663 // Get statscompanion service from service manager
664 const sp<IServiceManager> sm(defaultServiceManager());
665 if (sm != nullptr) {
666 const String16 name("statscompanion");
667 statsCompanion = interface_cast<IStatsCompanionService>(sm->checkService(name));
668 if (statsCompanion == nullptr) {
669 ALOGW("statscompanion service unavailable!");
670 return nullptr;
671 }
672 }
673 return statsCompanion;
674}
675
Yao Chenef99c4f2017-09-22 16:26:54 -0700676Status StatsService::statsCompanionReady() {
yro74fed972017-11-27 14:42:42 -0800677 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -0700678
679 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
680 return Status::fromExceptionCode(Status::EX_SECURITY,
681 "Only system uid can call statsCompanionReady");
682 }
683
684 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
685 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700686 return Status::fromExceptionCode(
687 Status::EX_NULL_POINTER,
688 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700689 }
yro74fed972017-11-27 14:42:42 -0800690 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700691 IInterface::asBinder(statsCompanion)->linkToDeath(new CompanionDeathRecipient(mAnomalyMonitor));
Bookatzb487b552017-09-18 11:26:01 -0700692 mAnomalyMonitor->setStatsCompanionService(statsCompanion);
693
694 return Status::ok();
695}
696
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700697void StatsService::Startup() {
698 mConfigManager->Startup();
Bookatz906a35c2017-09-20 15:26:44 -0700699}
700
Joe Onoratoc4dfae52017-10-17 23:38:21 -0700701void StatsService::OnLogEvent(const LogEvent& event) {
702 mProcessor->OnLogEvent(event);
Bookatz906a35c2017-09-20 15:26:44 -0700703}
704
Yangster7c334a12017-11-22 14:24:24 -0800705Status StatsService::getData(const String16& key, vector<uint8_t>* output) {
David Chenadaf8b32017-11-03 15:42:08 -0700706 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -0800707 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Yao Chen7ee94152017-11-17 09:44:40 -0800708 if (checkCallingPermission(String16(kPermissionDump))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800709 string keyStr = string(String8(key).string());
710 ConfigKey configKey(ipc->getCallingUid(), keyStr);
711 mProcessor->onDumpReport(configKey, output);
David Chenadaf8b32017-11-03 15:42:08 -0700712 return Status::ok();
713 } else {
714 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
715 }
yro31eb67b2017-10-24 13:33:21 -0700716}
717
David Chen2e8f3802017-11-22 10:56:48 -0800718Status StatsService::getMetadata(vector<uint8_t>* output) {
719 IPCThreadState* ipc = IPCThreadState::self();
720 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
721 ipc->getCallingUid());
722 if (checkCallingPermission(String16(kPermissionDump))) {
723 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
724 return Status::ok();
725 } else {
726 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
727 }
728}
729
David Chenadaf8b32017-11-03 15:42:08 -0700730Status StatsService::addConfiguration(const String16& key,
731 const vector <uint8_t>& config,
732 const String16& package, const String16& cls,
733 bool* success) {
734 IPCThreadState* ipc = IPCThreadState::self();
Yao Chen7ee94152017-11-17 09:44:40 -0800735 if (checkCallingPermission(String16(kPermissionDump))) {
David Chenadaf8b32017-11-03 15:42:08 -0700736 string keyString = string(String8(key).string());
David Chen1d7b0cd2017-11-15 14:20:04 -0800737 ConfigKey configKey(ipc->getCallingUid(), keyString);
David Chenadaf8b32017-11-03 15:42:08 -0700738 StatsdConfig cfg;
739 cfg.ParseFromArray(&config[0], config.size());
740 mConfigManager->UpdateConfig(configKey, cfg);
741 mConfigManager->SetConfigReceiver(configKey, string(String8(package).string()),
742 string(String8(cls).string()));
743 *success = true;
744 return Status::ok();
745 } else {
Yao Chenaa39bc72017-12-01 11:16:50 -0800746 *success = false;
David Chenadaf8b32017-11-03 15:42:08 -0700747 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
yro31eb67b2017-10-24 13:33:21 -0700748 }
yro31eb67b2017-10-24 13:33:21 -0700749}
750
David Chenadaf8b32017-11-03 15:42:08 -0700751Status StatsService::removeConfiguration(const String16& key, bool* success) {
752 IPCThreadState* ipc = IPCThreadState::self();
Yao Chen7ee94152017-11-17 09:44:40 -0800753 if (checkCallingPermission(String16(kPermissionDump))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800754 string keyStr = string(String8(key).string());
755 mConfigManager->RemoveConfig(ConfigKey(ipc->getCallingUid(), keyStr));
Yao Chenaa39bc72017-12-01 11:16:50 -0800756 *success = true;
David Chenadaf8b32017-11-03 15:42:08 -0700757 return Status::ok();
758 } else {
759 *success = false;
760 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
yro31eb67b2017-10-24 13:33:21 -0700761 }
yro31eb67b2017-10-24 13:33:21 -0700762}
763
David Chen1d7b0cd2017-11-15 14:20:04 -0800764void StatsService::binderDied(const wp <IBinder>& who) {
yro31eb67b2017-10-24 13:33:21 -0700765}
766
Yao Chenef99c4f2017-09-22 16:26:54 -0700767} // namespace statsd
768} // namespace os
769} // namespace android