blob: fb6f8c8d459097c034f28bb6ea7820ab29d4e0b4 [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
Tej Singh484524a2018-02-01 15:10:05 -080017#define DEBUG false // 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"
Yangster-mac330af582018-02-08 15:24:38 -080021#include "stats_log_util.h"
Yao Chen8d9989b2017-11-18 18:54:50 -080022#include "android-base/stringprintf.h"
David Chenadaf8b32017-11-03 15:42:08 -070023#include "config/ConfigKey.h"
24#include "config/ConfigManager.h"
Yao Chenb3561512017-11-21 18:07:17 -080025#include "guardrail/StatsdStats.h"
yro947fbce2017-11-15 22:50:23 -080026#include "storage/StorageManager.h"
Bookatzc6977972018-01-16 16:55:05 -080027#include "subscriber/SubscriberReporter.h"
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070028
David Chen0656b7a2017-09-13 15:53:39 -070029#include <android-base/file.h>
Jeff Sharkey6b649252018-04-16 09:50:22 -060030#include <android-base/stringprintf.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070031#include <binder/IPCThreadState.h>
32#include <binder/IServiceManager.h>
Jeff Sharkey6b649252018-04-16 09:50:22 -060033#include <binder/PermissionController.h>
yro87d983c2017-11-14 21:31:43 -080034#include <dirent.h>
David Chen0656b7a2017-09-13 15:53:39 -070035#include <frameworks/base/cmds/statsd/src/statsd_config.pb.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070036#include <private/android_filesystem_config.h>
Bookatzb223c4e2018-02-01 15:35:04 -080037#include <statslog.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070038#include <stdio.h>
Yao Chen482d2722017-09-12 13:25:43 -070039#include <stdlib.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070040#include <sys/system_properties.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070041#include <unistd.h>
Yao Chena80e5c02018-09-04 13:55:29 -070042#include <utils/Looper.h>
43#include <utils/String16.h>
44#include <chrono>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070045
46using namespace android;
47
Jeff Sharkey6b649252018-04-16 09:50:22 -060048using android::base::StringPrintf;
49
Bookatz906a35c2017-09-20 15:26:44 -070050namespace android {
51namespace os {
52namespace statsd {
53
David Chenadaf8b32017-11-03 15:42:08 -070054constexpr const char* kPermissionDump = "android.permission.DUMP";
Jeff Sharkey6b649252018-04-16 09:50:22 -060055constexpr const char* kPermissionUsage = "android.permission.PACKAGE_USAGE_STATS";
56
57constexpr const char* kOpUsage = "android:get_usage_stats";
58
yro03faf092017-12-12 00:17:50 -080059#define STATS_SERVICE_DIR "/data/misc/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070060
Jeff Sharkey6b649252018-04-16 09:50:22 -060061static binder::Status ok() {
62 return binder::Status::ok();
63}
64
65static binder::Status exception(uint32_t code, const std::string& msg) {
66 ALOGE("%s (%d)", msg.c_str(), code);
67 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
68}
69
70binder::Status checkUid(uid_t expectedUid) {
71 uid_t uid = IPCThreadState::self()->getCallingUid();
72 if (uid == expectedUid || uid == AID_ROOT) {
73 return ok();
74 } else {
75 return exception(binder::Status::EX_SECURITY,
76 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
77 }
78}
79
80binder::Status checkDumpAndUsageStats(const String16& packageName) {
81 pid_t pid = IPCThreadState::self()->getCallingPid();
82 uid_t uid = IPCThreadState::self()->getCallingUid();
83
84 // Root, system, and shell always have access
85 if (uid == AID_ROOT || uid == AID_SYSTEM || uid == AID_SHELL) {
86 return ok();
87 }
88
89 // Caller must be granted these permissions
90 if (!checkCallingPermission(String16(kPermissionDump))) {
91 return exception(binder::Status::EX_SECURITY,
92 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionDump));
93 }
94 if (!checkCallingPermission(String16(kPermissionUsage))) {
95 return exception(binder::Status::EX_SECURITY,
96 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionUsage));
97 }
98
99 // Caller must also have usage stats op granted
100 PermissionController pc;
101 switch (pc.noteOp(String16(kOpUsage), uid, packageName)) {
102 case PermissionController::MODE_ALLOWED:
103 case PermissionController::MODE_DEFAULT:
104 return ok();
105 default:
106 return exception(binder::Status::EX_SECURITY,
107 StringPrintf("UID %d / PID %d lacks app-op %s", uid, pid, kOpUsage));
108 }
109}
110
111#define ENFORCE_UID(uid) { \
112 binder::Status status = checkUid((uid)); \
113 if (!status.isOk()) { \
114 return status; \
115 } \
116}
117
118#define ENFORCE_DUMP_AND_USAGE_STATS(packageName) { \
119 binder::Status status = checkDumpAndUsageStats(packageName); \
120 if (!status.isOk()) { \
121 return status; \
122 } \
123}
124
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700125StatsService::StatsService(const sp<Looper>& handlerLooper)
Yangster-mac932ecec2018-02-01 10:23:52 -0800126 : mAnomalyAlarmMonitor(new AlarmMonitor(MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
127 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
128 if (sc != nullptr) {
129 sc->setAnomalyAlarm(timeMillis);
130 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
131 }
132 },
133 [](const sp<IStatsCompanionService>& sc) {
134 if (sc != nullptr) {
135 sc->cancelAnomalyAlarm();
136 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
137 }
138 })),
139 mPeriodicAlarmMonitor(new AlarmMonitor(MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
140 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
141 if (sc != nullptr) {
142 sc->setAlarmForSubscriberTriggering(timeMillis);
143 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
144 }
145 },
146 [](const sp<IStatsCompanionService>& sc) {
147 if (sc != nullptr) {
148 sc->cancelAlarmForSubscriberTriggering();
149 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
150 }
151
152 })) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700153 mUidMap = new UidMap();
Chenjie Yue2219202018-06-08 10:07:51 -0700154 mPullerManager = new StatsPullerManager();
Chenjie Yu80f91122018-01-31 20:24:50 -0800155 StatsPuller::SetUidMap(mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700156 mConfigManager = new ConfigManager();
Chenjie Yue2219202018-06-08 10:07:51 -0700157 mProcessor = new StatsLogProcessor(
158 mUidMap, mPullerManager, mAnomalyAlarmMonitor, mPeriodicAlarmMonitor,
159 getElapsedRealtimeNs(), [this](const ConfigKey& key) {
160 sp<IStatsCompanionService> sc = getStatsCompanionService();
161 auto receiver = mConfigManager->GetConfigReceiver(key);
162 if (sc == nullptr) {
163 VLOG("Could not find StatsCompanionService");
164 return false;
165 } else if (receiver == nullptr) {
166 VLOG("Statscompanion could not find a broadcast receiver for %s",
167 key.ToString().c_str());
168 return false;
169 } else {
170 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
171 return true;
172 }
173 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700174
175 mConfigManager->AddListener(mProcessor);
176
177 init_system_properties();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700178}
179
Yao Chenef99c4f2017-09-22 16:26:54 -0700180StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700181}
182
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700183void StatsService::init_system_properties() {
184 mEngBuild = false;
185 const prop_info* buildType = __system_property_find("ro.build.type");
186 if (buildType != NULL) {
187 __system_property_read_callback(buildType, init_build_type_callback, this);
188 }
David Chen0656b7a2017-09-13 15:53:39 -0700189}
190
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700191void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
192 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700193 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700194 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
195 }
196}
197
198/**
199 * Implement our own because the default binder implementation isn't
200 * properly handling SHELL_COMMAND_TRANSACTION.
201 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700202status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
203 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700204 switch (code) {
205 case SHELL_COMMAND_TRANSACTION: {
206 int in = data.readFileDescriptor();
207 int out = data.readFileDescriptor();
208 int err = data.readFileDescriptor();
209 int argc = data.readInt32();
210 Vector<String8> args;
211 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
212 args.add(String8(data.readString16()));
213 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700214 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
215 sp<IResultReceiver> resultReceiver =
216 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700217
Yao Chena80e5c02018-09-04 13:55:29 -0700218 err = command(in, out, err, args, resultReceiver);
219 resultReceiver->send(err);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700220 return NO_ERROR;
221 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700222 default: { return BnStatsManager::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700223 }
224}
225
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700226/**
227 * Write debugging data about statsd.
228 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700229status_t StatsService::dump(int fd, const Vector<String16>& args) {
Tej Singhdd83d702018-04-10 17:24:50 -0700230 if (!checkCallingPermission(String16(kPermissionDump))) {
231 return PERMISSION_DENIED;
232 }
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700233
Yao Chen884c8c12018-01-26 10:36:25 -0800234 bool verbose = false;
Tej Singh41b3f9a2018-04-03 17:06:35 -0700235 bool proto = false;
Yao Chen884c8c12018-01-26 10:36:25 -0800236 if (args.size() > 0 && !args[0].compare(String16("-v"))) {
237 verbose = true;
238 }
Tej Singh41b3f9a2018-04-03 17:06:35 -0700239 if (args.size() > 0 && !args[args.size()-1].compare(String16("--proto"))) {
240 proto = true;
241 }
Yao Chen884c8c12018-01-26 10:36:25 -0800242
Yao Chena80e5c02018-09-04 13:55:29 -0700243 dump_impl(fd, verbose, proto);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700244
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700245 return NO_ERROR;
246}
247
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700248/**
Tej Singh41b3f9a2018-04-03 17:06:35 -0700249 * Write debugging data about statsd in text or proto format.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700250 */
Yao Chena80e5c02018-09-04 13:55:29 -0700251void StatsService::dump_impl(int out, bool verbose, bool proto) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700252 if (proto) {
253 vector<uint8_t> data;
254 StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
255 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700256 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700257 }
258 } else {
259 StatsdStats::getInstance().dumpStats(out);
260 mProcessor->dumpStates(out, verbose);
261 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700262}
263
264/**
265 * Implementation of the adb shell cmd stats command.
266 */
Yao Chena80e5c02018-09-04 13:55:29 -0700267status_t StatsService::command(int in, int out, int err, Vector<String8>& args,
268 sp<IResultReceiver> resultReceiver) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600269 uid_t uid = IPCThreadState::self()->getCallingUid();
270 if (uid != AID_ROOT && uid != AID_SHELL) {
271 return PERMISSION_DENIED;
272 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700273
274 const int argCount = args.size();
275 if (argCount >= 1) {
276 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700277 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700278 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700279 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700280
David Chende701692017-10-05 13:16:02 -0700281 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800282 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700283 }
Yao Chen729093d2017-10-16 10:33:26 -0700284
285 if (!args[0].compare(String8("dump-report"))) {
286 return cmd_dump_report(out, err, args);
287 }
David Chen1481fe12017-10-16 13:16:34 -0700288
289 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
290 return cmd_print_pulled_metrics(out, args);
291 }
David Chenadaf8b32017-11-03 15:42:08 -0700292
293 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800294 return cmd_trigger_broadcast(out, args);
295 }
296
297 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800298 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700299 }
yro87d983c2017-11-14 21:31:43 -0800300
Yao Chen8d9989b2017-11-18 18:54:50 -0800301 if (!args[0].compare(String8("meminfo"))) {
302 return cmd_dump_memory_info(out);
303 }
yro947fbce2017-11-15 22:50:23 -0800304
305 if (!args[0].compare(String8("write-to-disk"))) {
306 return cmd_write_data_to_disk(out);
307 }
Bookatzb223c4e2018-02-01 15:35:04 -0800308
David Chen0b5c90c2018-01-25 16:51:49 -0800309 if (!args[0].compare(String8("log-app-breadcrumb"))) {
310 return cmd_log_app_breadcrumb(out, args);
Bookatzb223c4e2018-02-01 15:35:04 -0800311 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800312
313 if (!args[0].compare(String8("clear-puller-cache"))) {
314 return cmd_clear_puller_cache(out);
315 }
Yao Chen876889c2018-05-02 11:16:16 -0700316
317 if (!args[0].compare(String8("print-logs"))) {
318 return cmd_print_logs(out, args);
319 }
Yao Chena80e5c02018-09-04 13:55:29 -0700320 if (!args[0].compare(String8("data-subscribe"))) {
321 if (mShellSubscriber == nullptr) {
322 mShellSubscriber = new ShellSubscriber(mUidMap);
323 }
324 mShellSubscriber->startNewSubscription(in, out, resultReceiver);
325 return NO_ERROR;
326 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700327 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700328
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700329 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700330 return NO_ERROR;
331}
332
Yao Chena80e5c02018-09-04 13:55:29 -0700333void StatsService::print_cmd_help(int out) {
334 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700335 "usage: adb shell cmd stats print-stats-log [tag_required] "
336 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700337 dprintf(out, "\n");
338 dprintf(out, "\n");
339 dprintf(out, "usage: adb shell cmd stats meminfo\n");
340 dprintf(out, "\n");
341 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
342 dprintf(out, " # adb shell stop\n");
343 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
344 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
345 dprintf(out, " # adb shell start\n");
346 dprintf(out, "\n");
347 dprintf(out, "\n");
348 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
349 dprintf(out, "\n");
350 dprintf(out, " Prints the UID, app name, version mapping.\n");
351 dprintf(out, " PKG Optional package name to print the uids of the package\n");
352 dprintf(out, "\n");
353 dprintf(out, "\n");
354 dprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
355 dprintf(out, "\n");
356 dprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
357 dprintf(out, "\n");
358 dprintf(out, "\n");
359 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
360 dprintf(out, "\n");
361 dprintf(out, " Flushes all data on memory to disk.\n");
362 dprintf(out, "\n");
363 dprintf(out, "\n");
364 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
365 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
366 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
367 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
368 dprintf(out, " uid is used.\n");
369 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
370 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
371 dprintf(out, "\n");
372 dprintf(out, "\n");
373 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
374 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
375 dprintf(out, "\n");
376 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
377 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
378 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
379 dprintf(out, "\n");
380 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
381 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
382 dprintf(out, " uid is used.\n");
383 dprintf(out, " NAME The per-uid name to use\n");
384 dprintf(out, "\n");
385 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
386 dprintf(out, "\n be removed from memory and disk!\n");
387 dprintf(out, "\n");
388 dprintf(out,
389 "usage: adb shell cmd stats dump-report [UID] NAME [--include_current_bucket] "
390 "[--proto]\n");
391 dprintf(out, " Dump all metric data for a configuration.\n");
392 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
393 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
394 dprintf(out, " calling uid is used.\n");
395 dprintf(out, " NAME The name of the configuration\n");
396 dprintf(out, " --proto Print proto binary.\n");
397 dprintf(out, "\n");
398 dprintf(out, "\n");
399 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
400 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
401 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
402 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
403 dprintf(out, " calling uid is used.\n");
404 dprintf(out, " NAME The name of the configuration\n");
405 dprintf(out, "\n");
406 dprintf(out, "\n");
407 dprintf(out, "usage: adb shell cmd stats print-stats\n");
408 dprintf(out, " Prints some basic stats.\n");
409 dprintf(out, " --proto Print proto binary instead of string format.\n");
410 dprintf(out, "\n");
411 dprintf(out, "\n");
412 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
413 dprintf(out, " Clear cached puller data.\n");
414 dprintf(out, "\n");
415 dprintf(out, "usage: adb shell cmd stats print-logs\n");
416 dprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700417}
418
Yao Chena80e5c02018-09-04 13:55:29 -0700419status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800420 string name;
421 bool good = false;
422 int uid;
423 const int argCount = args.size();
424 if (argCount == 2) {
425 // Automatically pick the UID
426 uid = IPCThreadState::self()->getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800427 name.assign(args[1].c_str(), args[1].size());
428 good = true;
429 } else if (argCount == 3) {
430 // If it's a userdebug or eng build, then the shell user can
431 // impersonate other uids.
432 if (mEngBuild) {
433 const char* s = args[1].c_str();
434 if (*s != '\0') {
435 char* end = NULL;
436 uid = strtol(s, &end, 0);
437 if (*end == '\0') {
438 name.assign(args[2].c_str(), args[2].size());
439 good = true;
440 }
441 }
442 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700443 dprintf(out,
David Chen1d7b0cd2017-11-15 14:20:04 -0800444 "The metrics can only be dumped for other UIDs on eng or userdebug "
Yao Chena80e5c02018-09-04 13:55:29 -0700445 "builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800446 }
447 }
448 if (!good) {
449 print_cmd_help(out);
450 return UNKNOWN_ERROR;
451 }
David Chend37bc232018-04-12 18:05:11 -0700452 ConfigKey key(uid, StrToInt64(name));
453 auto receiver = mConfigManager->GetConfigReceiver(key);
yro4d889e62017-11-17 15:44:48 -0800454 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen661f7912018-01-22 17:46:24 -0800455 if (sc == nullptr) {
456 VLOG("Could not access statsCompanion");
457 } else if (receiver == nullptr) {
458 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str())
459 } else {
David Chend37bc232018-04-12 18:05:11 -0700460 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
yro74fed972017-11-27 14:42:42 -0800461 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
462 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800463 }
464
David Chenadaf8b32017-11-03 15:42:08 -0700465 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700466}
467
Yao Chena80e5c02018-09-04 13:55:29 -0700468status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700469 const int argCount = args.size();
470 if (argCount >= 2) {
471 if (args[1] == "update" || args[1] == "remove") {
472 bool good = false;
473 int uid = -1;
474 string name;
475
476 if (argCount == 3) {
477 // Automatically pick the UID
478 uid = IPCThreadState::self()->getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700479 name.assign(args[2].c_str(), args[2].size());
480 good = true;
481 } else if (argCount == 4) {
482 // If it's a userdebug or eng build, then the shell user can
483 // impersonate other uids.
484 if (mEngBuild) {
485 const char* s = args[2].c_str();
486 if (*s != '\0') {
487 char* end = NULL;
488 uid = strtol(s, &end, 0);
489 if (*end == '\0') {
490 name.assign(args[3].c_str(), args[3].size());
491 good = true;
492 }
493 }
494 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700495 dprintf(err,
Yao Chen729093d2017-10-16 10:33:26 -0700496 "The config can only be set for other UIDs on eng or userdebug "
497 "builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700498 }
yroe5f82922018-01-22 18:37:27 -0800499 } else if (argCount == 2 && args[1] == "remove") {
500 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700501 }
502
503 if (!good) {
504 // If arg parsing failed, print the help text and return an error.
505 print_cmd_help(out);
506 return UNKNOWN_ERROR;
507 }
508
509 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800510 char* endp;
511 int64_t configID = strtoll(name.c_str(), &endp, 10);
512 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700513 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800514 return UNKNOWN_ERROR;
515 }
516
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700517 // Read stream into buffer.
518 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700519 if (!android::base::ReadFdToString(in, &buffer)) {
520 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700521 return UNKNOWN_ERROR;
522 }
523
524 // Parse buffer.
525 StatsdConfig config;
526 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700527 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700528 return UNKNOWN_ERROR;
529 }
530
531 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800532 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700533 } else {
yro74fed972017-11-27 14:42:42 -0800534 if (argCount == 2) {
535 cmd_remove_all_configs(out);
536 } else {
537 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800538 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800539 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700540 }
541
542 return NO_ERROR;
543 }
David Chen0656b7a2017-09-13 15:53:39 -0700544 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700545 print_cmd_help(out);
546 return UNKNOWN_ERROR;
547}
548
Yao Chena80e5c02018-09-04 13:55:29 -0700549status_t StatsService::cmd_dump_report(int out, int err, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700550 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800551 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700552 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800553 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700554 bool includeCurrentBucket = false;
Yao Chen729093d2017-10-16 10:33:26 -0700555 int uid;
556 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800557 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
558 proto = true;
559 argCount -= 1;
560 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700561 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
562 includeCurrentBucket = true;
563 argCount -= 1;
564 }
Yao Chen729093d2017-10-16 10:33:26 -0700565 if (argCount == 2) {
566 // Automatically pick the UID
567 uid = IPCThreadState::self()->getCallingUid();
Yao Chen5154a3792017-10-30 22:57:06 -0700568 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700569 good = true;
570 } else if (argCount == 3) {
571 // If it's a userdebug or eng build, then the shell user can
572 // impersonate other uids.
573 if (mEngBuild) {
574 const char* s = args[1].c_str();
575 if (*s != '\0') {
576 char* end = NULL;
577 uid = strtol(s, &end, 0);
578 if (*end == '\0') {
579 name.assign(args[2].c_str(), args[2].size());
580 good = true;
581 }
582 }
583 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700584 dprintf(out,
Yao Chen729093d2017-10-16 10:33:26 -0700585 "The metrics can only be dumped for other UIDs on eng or userdebug "
586 "builds.\n");
587 }
588 }
589 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800590 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800591 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700592 includeCurrentBucket, ADB_DUMP, &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800593 if (proto) {
594 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700595 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800596 }
597 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700598 dprintf(out, "Dump report for Config [%d,%s]\n", uid, name.c_str());
599 dprintf(out, "See the StatsLogReport in logcat...\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800600 }
Yao Chen729093d2017-10-16 10:33:26 -0700601 return android::OK;
602 } else {
603 // If arg parsing failed, print the help text and return an error.
604 print_cmd_help(out);
605 return UNKNOWN_ERROR;
606 }
607 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700608 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700609 return UNKNOWN_ERROR;
610 }
611}
612
Yao Chena80e5c02018-09-04 13:55:29 -0700613status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700614 int argCount = args.size();
615 bool proto = false;
616 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
617 proto = true;
618 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800619 }
Yao Chenb3561512017-11-21 18:07:17 -0800620 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700621 if (proto) {
622 vector<uint8_t> data;
623 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
624 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700625 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700626 }
627
628 } else {
629 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
630 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700631 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700632 mProcessor->GetMetricsSize(key));
633 }
634 statsdStats.dumpStats(out);
635 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800636 return NO_ERROR;
637}
638
Yao Chena80e5c02018-09-04 13:55:29 -0700639status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800640 if (args.size() > 1) {
641 string pkg;
642 pkg.assign(args[1].c_str(), args[1].size());
643 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700644 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800645 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700646 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800647 }
Yao Chena80e5c02018-09-04 13:55:29 -0700648 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800649 } else {
650 mUidMap->printUidMap(out);
651 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700652 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700653}
654
Yao Chena80e5c02018-09-04 13:55:29 -0700655status_t StatsService::cmd_write_data_to_disk(int out) {
656 dprintf(out, "Writing data to disk\n");
Yangster-mac892f3d32018-05-02 14:16:48 -0700657 mProcessor->WriteDataToDisk(ADB_DUMP);
yro947fbce2017-11-15 22:50:23 -0800658 return NO_ERROR;
659}
660
Yao Chena80e5c02018-09-04 13:55:29 -0700661status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800662 bool good = false;
663 int32_t uid;
664 int32_t label;
665 int32_t state;
666 const int argCount = args.size();
667 if (argCount == 3) {
668 // Automatically pick the UID
669 uid = IPCThreadState::self()->getCallingUid();
670 label = atoi(args[1].c_str());
671 state = atoi(args[2].c_str());
672 good = true;
673 } else if (argCount == 4) {
674 uid = atoi(args[1].c_str());
675 // If it's a userdebug or eng build, then the shell user can impersonate other uids.
676 // Otherwise, the uid must match the actual caller's uid.
677 if (mEngBuild || (uid >= 0 && (uid_t)uid == IPCThreadState::self()->getCallingUid())) {
678 label = atoi(args[2].c_str());
679 state = atoi(args[3].c_str());
680 good = true;
681 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700682 dprintf(out,
David Chenb639d142018-02-14 17:29:54 -0800683 "Selecting a UID for writing AppBreadcrumb can only be done for other UIDs "
Yao Chena80e5c02018-09-04 13:55:29 -0700684 "on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800685 }
686 }
687 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700688 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
David Chen0b5c90c2018-01-25 16:51:49 -0800689 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800690 } else {
691 print_cmd_help(out);
692 return UNKNOWN_ERROR;
693 }
694 return NO_ERROR;
695}
696
Yao Chena80e5c02018-09-04 13:55:29 -0700697status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700698 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700699 vector<shared_ptr<LogEvent> > stats;
Chenjie Yue2219202018-06-08 10:07:51 -0700700 if (mPullerManager->Pull(s, getElapsedRealtimeNs(), &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700701 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700702 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700703 }
Yao Chena80e5c02018-09-04 13:55:29 -0700704 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700705 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700706 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700707 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700708}
709
Yao Chena80e5c02018-09-04 13:55:29 -0700710status_t StatsService::cmd_remove_all_configs(int out) {
711 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800712 VLOG("StatsService::cmd_remove_all_configs was called");
713 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800714 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800715 return NO_ERROR;
716}
717
Yao Chena80e5c02018-09-04 13:55:29 -0700718status_t StatsService::cmd_dump_memory_info(int out) {
719 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800720 return NO_ERROR;
721}
722
Yao Chena80e5c02018-09-04 13:55:29 -0700723status_t StatsService::cmd_clear_puller_cache(int out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800724 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800725 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
726 ipc->getCallingPid(), ipc->getCallingUid());
Chenjie Yufa22d652018-02-05 14:37:48 -0800727 if (checkCallingPermission(String16(kPermissionDump))) {
Chenjie Yue2219202018-06-08 10:07:51 -0700728 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700729 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800730 return NO_ERROR;
731 } else {
732 return PERMISSION_DENIED;
733 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800734}
735
Yao Chena80e5c02018-09-04 13:55:29 -0700736status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Yao Chen876889c2018-05-02 11:16:16 -0700737 IPCThreadState* ipc = IPCThreadState::self();
738 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", ipc->getCallingPid(),
739 ipc->getCallingUid());
740 if (checkCallingPermission(String16(kPermissionDump))) {
741 bool enabled = true;
742 if (args.size() >= 2) {
743 enabled = atoi(args[1].c_str()) != 0;
744 }
745 mProcessor->setPrintLogs(enabled);
746 return NO_ERROR;
747 } else {
748 return PERMISSION_DENIED;
749 }
750}
751
Dianne Hackborn3accca02013-09-20 09:32:11 -0700752Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int64_t>& version,
David Chende701692017-10-05 13:16:02 -0700753 const vector<String16>& app) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600754 ENFORCE_UID(AID_SYSTEM);
755
yro74fed972017-11-27 14:42:42 -0800756 VLOG("StatsService::informAllUidData was called");
David Chenbd125272018-04-04 19:02:50 -0700757 mUidMap->updateMap(getElapsedRealtimeNs(), uid, version, app);
yro74fed972017-11-27 14:42:42 -0800758 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700759
760 return Status::ok();
761}
762
Dianne Hackborn3accca02013-09-20 09:32:11 -0700763Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600764 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700765
Jeff Sharkey6b649252018-04-16 09:50:22 -0600766 VLOG("StatsService::informOnePackage was called");
David Chenbd125272018-04-04 19:02:50 -0700767 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version);
David Chende701692017-10-05 13:16:02 -0700768 return Status::ok();
769}
770
771Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600772 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700773
Jeff Sharkey6b649252018-04-16 09:50:22 -0600774 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -0700775 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -0800776 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -0700777 return Status::ok();
778}
779
Yao Chenef99c4f2017-09-22 16:26:54 -0700780Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600781 ENFORCE_UID(AID_SYSTEM);
782
yro74fed972017-11-27 14:42:42 -0800783 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700784 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800785 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
786 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
787 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -0800788 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -0800789 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -0800790 } else {
791 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
792 }
Bookatz1b0b1142017-09-08 11:58:42 -0700793 return Status::ok();
794}
795
Yangster-mac932ecec2018-02-01 10:23:52 -0800796Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600797 ENFORCE_UID(AID_SYSTEM);
798
Yangster-mac932ecec2018-02-01 10:23:52 -0800799 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700800 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800801 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
802 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
803 if (alarmSet.size() > 0) {
804 VLOG("Found periodic alarm fired.");
805 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
806 } else {
807 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
808 }
809 return Status::ok();
810}
811
Yao Chenef99c4f2017-09-22 16:26:54 -0700812Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600813 ENFORCE_UID(AID_SYSTEM);
814
yro74fed972017-11-27 14:42:42 -0800815 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700816 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -0800817 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700818 return Status::ok();
819}
820
Yao Chenef99c4f2017-09-22 16:26:54 -0700821Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600822 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700823
824 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800825 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -0700826 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700827 return Status::ok();
828}
829
Yangster-mac892f3d32018-05-02 14:16:48 -0700830Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600831 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -0700832 VLOG("StatsService::informDeviceShutdown");
Yangster-mac892f3d32018-05-02 14:16:48 -0700833 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN);
yro947fbce2017-11-15 22:50:23 -0800834 return Status::ok();
835}
836
Yao Chenef99c4f2017-09-22 16:26:54 -0700837void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -0700838 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
839 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -0800840 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -0700841 statsCompanion->statsdReady();
842 } else {
yro74fed972017-11-27 14:42:42 -0800843 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -0700844 }
845}
846
Yao Chenef99c4f2017-09-22 16:26:54 -0700847Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600848 ENFORCE_UID(AID_SYSTEM);
849
yro74fed972017-11-27 14:42:42 -0800850 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -0700851 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
852 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700853 return Status::fromExceptionCode(
854 Status::EX_NULL_POINTER,
855 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700856 }
yro74fed972017-11-27 14:42:42 -0800857 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -0700858 IInterface::asBinder(statsCompanion)->linkToDeath(this);
Chenjie Yue2219202018-06-08 10:07:51 -0700859 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -0800860 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
861 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -0800862 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -0700863 return Status::ok();
864}
865
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700866void StatsService::Startup() {
867 mConfigManager->Startup();
Bookatz906a35c2017-09-20 15:26:44 -0700868}
869
Yangster-mac97e7d202018-10-09 11:05:39 -0700870void StatsService::Terminate() {
871 ALOGI("StatsService::Terminating");
872 if (mProcessor != nullptr) {
873 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED);
874 }
875}
876
Yao Chen3ff3a492018-08-06 16:17:37 -0700877void StatsService::OnLogEvent(LogEvent* event) {
878 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -0700879 if (mShellSubscriber != nullptr) {
880 mShellSubscriber->onLogEvent(*event);
881 }
Bookatz906a35c2017-09-20 15:26:44 -0700882}
883
Jeff Sharkey6b649252018-04-16 09:50:22 -0600884Status StatsService::getData(int64_t key, const String16& packageName, vector<uint8_t>* output) {
885 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
886
David Chenadaf8b32017-11-03 15:42:08 -0700887 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -0800888 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -0700889 ConfigKey configKey(ipc->getCallingUid(), key);
David Chen56ae0d92018-05-11 16:00:22 -0700890 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
891 GET_DATA_CALLED, output);
Bookatz4f716292018-04-10 17:15:12 -0700892 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700893}
894
Jeff Sharkey6b649252018-04-16 09:50:22 -0600895Status StatsService::getMetadata(const String16& packageName, vector<uint8_t>* output) {
896 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
897
David Chen2e8f3802017-11-22 10:56:48 -0800898 IPCThreadState* ipc = IPCThreadState::self();
899 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
900 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -0700901 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
902 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -0800903}
904
Jeff Sharkey6b649252018-04-16 09:50:22 -0600905Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
906 const String16& packageName) {
907 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
908
David Chenadaf8b32017-11-03 15:42:08 -0700909 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -0700910 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -0800911 return Status::ok();
912 } else {
Bookatz4f716292018-04-10 17:15:12 -0700913 ALOGE("Could not parse malformatted StatsdConfig");
914 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
915 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -0800916 }
917}
918
David Chen9fdd4032018-03-20 14:38:56 -0700919bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
920 ConfigKey configKey(uid, key);
921 StatsdConfig cfg;
922 if (config.size() > 0) { // If the config is empty, skip parsing.
923 if (!cfg.ParseFromArray(&config[0], config.size())) {
924 return false;
925 }
926 }
927 mConfigManager->UpdateConfig(configKey, cfg);
928 return true;
929}
930
Jeff Sharkey6b649252018-04-16 09:50:22 -0600931Status StatsService::removeDataFetchOperation(int64_t key, const String16& packageName) {
932 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
933
Bookatz4f716292018-04-10 17:15:12 -0700934 IPCThreadState* ipc = IPCThreadState::self();
935 ConfigKey configKey(ipc->getCallingUid(), key);
936 mConfigManager->RemoveConfigReceiver(configKey);
937 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -0800938}
939
Jeff Sharkey6b649252018-04-16 09:50:22 -0600940Status StatsService::setDataFetchOperation(int64_t key,
941 const sp<android::IBinder>& intentSender,
942 const String16& packageName) {
943 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
944
Bookatz4f716292018-04-10 17:15:12 -0700945 IPCThreadState* ipc = IPCThreadState::self();
946 ConfigKey configKey(ipc->getCallingUid(), key);
947 mConfigManager->SetConfigReceiver(configKey, intentSender);
David Chen48944902018-05-03 10:29:11 -0700948 if (StorageManager::hasConfigMetricsReport(configKey)) {
949 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
950 configKey.ToString().c_str());
951 mProcessor->noteOnDiskData(configKey);
952 }
Bookatz4f716292018-04-10 17:15:12 -0700953 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700954}
955
Jeff Sharkey6b649252018-04-16 09:50:22 -0600956Status StatsService::removeConfiguration(int64_t key, const String16& packageName) {
957 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
958
Bookatz4f716292018-04-10 17:15:12 -0700959 IPCThreadState* ipc = IPCThreadState::self();
960 ConfigKey configKey(ipc->getCallingUid(), key);
961 mConfigManager->RemoveConfig(configKey);
962 SubscriberReporter::getInstance().removeConfig(configKey);
963 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700964}
965
Bookatzc6977972018-01-16 16:55:05 -0800966Status StatsService::setBroadcastSubscriber(int64_t configId,
967 int64_t subscriberId,
Jeff Sharkey6b649252018-04-16 09:50:22 -0600968 const sp<android::IBinder>& intentSender,
969 const String16& packageName) {
970 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
971
Bookatzc6977972018-01-16 16:55:05 -0800972 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -0700973 IPCThreadState* ipc = IPCThreadState::self();
974 ConfigKey configKey(ipc->getCallingUid(), configId);
975 SubscriberReporter::getInstance()
976 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
977 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -0800978}
979
980Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -0600981 int64_t subscriberId,
982 const String16& packageName) {
983 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
984
Bookatzc6977972018-01-16 16:55:05 -0800985 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -0700986 IPCThreadState* ipc = IPCThreadState::self();
987 ConfigKey configKey(ipc->getCallingUid(), configId);
988 SubscriberReporter::getInstance()
989 .unsetBroadcastSubscriber(configKey, subscriberId);
990 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -0800991}
992
yrobe6d7f92018-05-04 13:02:53 -0700993Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
994 // Permission check not necessary as it's meant for applications to write to
995 // statsd.
996 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
997 IPCThreadState::self()->getCallingUid(), label,
998 state);
999 return Status::ok();
1000}
1001
Howard Roa46b6582018-09-18 16:45:02 -07001002hardware::Return<void> StatsService::reportSpeakerImpedance(
1003 const SpeakerImpedance& speakerImpedance) {
1004 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), speakerImpedance);
1005 mProcessor->OnLogEvent(&event);
1006
1007 return hardware::Void();
1008}
1009
1010hardware::Return<void> StatsService::reportHardwareFailed(const HardwareFailed& hardwareFailed) {
1011 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), hardwareFailed);
1012 mProcessor->OnLogEvent(&event);
1013
1014 return hardware::Void();
1015}
1016
1017hardware::Return<void> StatsService::reportPhysicalDropDetected(
1018 const PhysicalDropDetected& physicalDropDetected) {
1019 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), physicalDropDetected);
1020 mProcessor->OnLogEvent(&event);
1021
1022 return hardware::Void();
1023}
1024
1025hardware::Return<void> StatsService::reportChargeCycles(const ChargeCycles& chargeCycles) {
1026 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), chargeCycles);
1027 mProcessor->OnLogEvent(&event);
1028
1029 return hardware::Void();
1030}
1031
1032hardware::Return<void> StatsService::reportBatteryHealthSnapshot(
1033 const BatteryHealthSnapshotArgs& batteryHealthSnapshotArgs) {
1034 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(),
1035 batteryHealthSnapshotArgs);
1036 mProcessor->OnLogEvent(&event);
1037
1038 return hardware::Void();
1039}
1040
1041hardware::Return<void> StatsService::reportSlowIo(const SlowIo& slowIo) {
1042 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), slowIo);
1043 mProcessor->OnLogEvent(&event);
1044
1045 return hardware::Void();
1046}
1047
1048hardware::Return<void> StatsService::reportBatteryCausedShutdown(
1049 const BatteryCausedShutdown& batteryCausedShutdown) {
1050 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), batteryCausedShutdown);
1051 mProcessor->OnLogEvent(&event);
1052
1053 return hardware::Void();
1054}
1055
David Chen1d7b0cd2017-11-15 14:20:04 -08001056void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001057 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001058 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1059 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001060 ALOGW("Reset statsd upon system server restarts.");
Yangster-mac892f3d32018-05-02 14:16:48 -07001061 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED);
1062 mProcessor->resetConfigs();
1063 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001064 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1065 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
1066 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001067 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001068}
1069
Yao Chenef99c4f2017-09-22 16:26:54 -07001070} // namespace statsd
1071} // namespace os
1072} // namespace android