blob: 148e1472a9601d85e0dd006a8a2497b8f491b0ac [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) {
Yao Chen41e606c2018-10-05 15:54:11 -0700322 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
Yao Chena80e5c02018-09-04 13:55:29 -0700323 }
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,
dwchen730403e2018-10-29 11:41:56 -0700753 const vector<String16>& version_string,
754 const vector<String16>& app,
755 const vector<String16>& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600756 ENFORCE_UID(AID_SYSTEM);
757
yro74fed972017-11-27 14:42:42 -0800758 VLOG("StatsService::informAllUidData was called");
dwchen730403e2018-10-29 11:41:56 -0700759 mUidMap->updateMap(getElapsedRealtimeNs(), uid, version, version_string, app, installer);
yro74fed972017-11-27 14:42:42 -0800760 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700761
762 return Status::ok();
763}
764
dwchen730403e2018-10-29 11:41:56 -0700765Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version,
766 const String16& version_string, const String16& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600767 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700768
Jeff Sharkey6b649252018-04-16 09:50:22 -0600769 VLOG("StatsService::informOnePackage was called");
dwchen730403e2018-10-29 11:41:56 -0700770 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version, version_string, installer);
David Chende701692017-10-05 13:16:02 -0700771 return Status::ok();
772}
773
774Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600775 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700776
Jeff Sharkey6b649252018-04-16 09:50:22 -0600777 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -0700778 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -0800779 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -0700780 return Status::ok();
781}
782
Yao Chenef99c4f2017-09-22 16:26:54 -0700783Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600784 ENFORCE_UID(AID_SYSTEM);
785
yro74fed972017-11-27 14:42:42 -0800786 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700787 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800788 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
789 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
790 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -0800791 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -0800792 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -0800793 } else {
794 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
795 }
Bookatz1b0b1142017-09-08 11:58:42 -0700796 return Status::ok();
797}
798
Yangster-mac932ecec2018-02-01 10:23:52 -0800799Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600800 ENFORCE_UID(AID_SYSTEM);
801
Yangster-mac932ecec2018-02-01 10:23:52 -0800802 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700803 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800804 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
805 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
806 if (alarmSet.size() > 0) {
807 VLOG("Found periodic alarm fired.");
808 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
809 } else {
810 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
811 }
812 return Status::ok();
813}
814
Yao Chenef99c4f2017-09-22 16:26:54 -0700815Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600816 ENFORCE_UID(AID_SYSTEM);
817
yro74fed972017-11-27 14:42:42 -0800818 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700819 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -0800820 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700821 return Status::ok();
822}
823
Yao Chenef99c4f2017-09-22 16:26:54 -0700824Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600825 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700826
827 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800828 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -0700829 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700830 return Status::ok();
831}
832
Yangster-mac892f3d32018-05-02 14:16:48 -0700833Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600834 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -0700835 VLOG("StatsService::informDeviceShutdown");
Yangster-mac892f3d32018-05-02 14:16:48 -0700836 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN);
yro947fbce2017-11-15 22:50:23 -0800837 return Status::ok();
838}
839
Yao Chenef99c4f2017-09-22 16:26:54 -0700840void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -0700841 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
842 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -0800843 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -0700844 statsCompanion->statsdReady();
845 } else {
yro74fed972017-11-27 14:42:42 -0800846 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -0700847 }
848}
849
Yao Chenef99c4f2017-09-22 16:26:54 -0700850Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600851 ENFORCE_UID(AID_SYSTEM);
852
yro74fed972017-11-27 14:42:42 -0800853 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -0700854 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
855 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700856 return Status::fromExceptionCode(
857 Status::EX_NULL_POINTER,
858 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700859 }
yro74fed972017-11-27 14:42:42 -0800860 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -0700861 IInterface::asBinder(statsCompanion)->linkToDeath(this);
Chenjie Yue2219202018-06-08 10:07:51 -0700862 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -0800863 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
864 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -0800865 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -0700866 return Status::ok();
867}
868
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700869void StatsService::Startup() {
870 mConfigManager->Startup();
Bookatz906a35c2017-09-20 15:26:44 -0700871}
872
Yangster-mac97e7d202018-10-09 11:05:39 -0700873void StatsService::Terminate() {
874 ALOGI("StatsService::Terminating");
875 if (mProcessor != nullptr) {
876 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED);
877 }
878}
879
Yao Chen3ff3a492018-08-06 16:17:37 -0700880void StatsService::OnLogEvent(LogEvent* event) {
881 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -0700882 if (mShellSubscriber != nullptr) {
883 mShellSubscriber->onLogEvent(*event);
884 }
Bookatz906a35c2017-09-20 15:26:44 -0700885}
886
Jeff Sharkey6b649252018-04-16 09:50:22 -0600887Status StatsService::getData(int64_t key, const String16& packageName, vector<uint8_t>* output) {
888 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
889
David Chenadaf8b32017-11-03 15:42:08 -0700890 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -0800891 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -0700892 ConfigKey configKey(ipc->getCallingUid(), key);
David Chen56ae0d92018-05-11 16:00:22 -0700893 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
894 GET_DATA_CALLED, output);
Bookatz4f716292018-04-10 17:15:12 -0700895 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700896}
897
Jeff Sharkey6b649252018-04-16 09:50:22 -0600898Status StatsService::getMetadata(const String16& packageName, vector<uint8_t>* output) {
899 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
900
David Chen2e8f3802017-11-22 10:56:48 -0800901 IPCThreadState* ipc = IPCThreadState::self();
902 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
903 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -0700904 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
905 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -0800906}
907
Jeff Sharkey6b649252018-04-16 09:50:22 -0600908Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
909 const String16& packageName) {
910 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
911
David Chenadaf8b32017-11-03 15:42:08 -0700912 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -0700913 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -0800914 return Status::ok();
915 } else {
Bookatz4f716292018-04-10 17:15:12 -0700916 ALOGE("Could not parse malformatted StatsdConfig");
917 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
918 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -0800919 }
920}
921
David Chen9fdd4032018-03-20 14:38:56 -0700922bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
923 ConfigKey configKey(uid, key);
924 StatsdConfig cfg;
925 if (config.size() > 0) { // If the config is empty, skip parsing.
926 if (!cfg.ParseFromArray(&config[0], config.size())) {
927 return false;
928 }
929 }
930 mConfigManager->UpdateConfig(configKey, cfg);
931 return true;
932}
933
Jeff Sharkey6b649252018-04-16 09:50:22 -0600934Status StatsService::removeDataFetchOperation(int64_t key, const String16& packageName) {
935 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
936
Bookatz4f716292018-04-10 17:15:12 -0700937 IPCThreadState* ipc = IPCThreadState::self();
938 ConfigKey configKey(ipc->getCallingUid(), key);
939 mConfigManager->RemoveConfigReceiver(configKey);
940 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -0800941}
942
Jeff Sharkey6b649252018-04-16 09:50:22 -0600943Status StatsService::setDataFetchOperation(int64_t key,
944 const sp<android::IBinder>& intentSender,
945 const String16& packageName) {
946 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
947
Bookatz4f716292018-04-10 17:15:12 -0700948 IPCThreadState* ipc = IPCThreadState::self();
949 ConfigKey configKey(ipc->getCallingUid(), key);
950 mConfigManager->SetConfigReceiver(configKey, intentSender);
David Chen48944902018-05-03 10:29:11 -0700951 if (StorageManager::hasConfigMetricsReport(configKey)) {
952 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
953 configKey.ToString().c_str());
954 mProcessor->noteOnDiskData(configKey);
955 }
Bookatz4f716292018-04-10 17:15:12 -0700956 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700957}
958
Jeff Sharkey6b649252018-04-16 09:50:22 -0600959Status StatsService::removeConfiguration(int64_t key, const String16& packageName) {
960 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
961
Bookatz4f716292018-04-10 17:15:12 -0700962 IPCThreadState* ipc = IPCThreadState::self();
963 ConfigKey configKey(ipc->getCallingUid(), key);
964 mConfigManager->RemoveConfig(configKey);
965 SubscriberReporter::getInstance().removeConfig(configKey);
966 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700967}
968
Bookatzc6977972018-01-16 16:55:05 -0800969Status StatsService::setBroadcastSubscriber(int64_t configId,
970 int64_t subscriberId,
Jeff Sharkey6b649252018-04-16 09:50:22 -0600971 const sp<android::IBinder>& intentSender,
972 const String16& packageName) {
973 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
974
Bookatzc6977972018-01-16 16:55:05 -0800975 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -0700976 IPCThreadState* ipc = IPCThreadState::self();
977 ConfigKey configKey(ipc->getCallingUid(), configId);
978 SubscriberReporter::getInstance()
979 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
980 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -0800981}
982
983Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -0600984 int64_t subscriberId,
985 const String16& packageName) {
986 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
987
Bookatzc6977972018-01-16 16:55:05 -0800988 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -0700989 IPCThreadState* ipc = IPCThreadState::self();
990 ConfigKey configKey(ipc->getCallingUid(), configId);
991 SubscriberReporter::getInstance()
992 .unsetBroadcastSubscriber(configKey, subscriberId);
993 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -0800994}
995
yrobe6d7f92018-05-04 13:02:53 -0700996Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
997 // Permission check not necessary as it's meant for applications to write to
998 // statsd.
999 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
1000 IPCThreadState::self()->getCallingUid(), label,
1001 state);
1002 return Status::ok();
1003}
1004
Howard Roa46b6582018-09-18 16:45:02 -07001005hardware::Return<void> StatsService::reportSpeakerImpedance(
1006 const SpeakerImpedance& speakerImpedance) {
1007 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), speakerImpedance);
1008 mProcessor->OnLogEvent(&event);
1009
1010 return hardware::Void();
1011}
1012
1013hardware::Return<void> StatsService::reportHardwareFailed(const HardwareFailed& hardwareFailed) {
1014 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), hardwareFailed);
1015 mProcessor->OnLogEvent(&event);
1016
1017 return hardware::Void();
1018}
1019
1020hardware::Return<void> StatsService::reportPhysicalDropDetected(
1021 const PhysicalDropDetected& physicalDropDetected) {
1022 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), physicalDropDetected);
1023 mProcessor->OnLogEvent(&event);
1024
1025 return hardware::Void();
1026}
1027
1028hardware::Return<void> StatsService::reportChargeCycles(const ChargeCycles& chargeCycles) {
1029 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), chargeCycles);
1030 mProcessor->OnLogEvent(&event);
1031
1032 return hardware::Void();
1033}
1034
1035hardware::Return<void> StatsService::reportBatteryHealthSnapshot(
1036 const BatteryHealthSnapshotArgs& batteryHealthSnapshotArgs) {
1037 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(),
1038 batteryHealthSnapshotArgs);
1039 mProcessor->OnLogEvent(&event);
1040
1041 return hardware::Void();
1042}
1043
1044hardware::Return<void> StatsService::reportSlowIo(const SlowIo& slowIo) {
1045 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), slowIo);
1046 mProcessor->OnLogEvent(&event);
1047
1048 return hardware::Void();
1049}
1050
1051hardware::Return<void> StatsService::reportBatteryCausedShutdown(
1052 const BatteryCausedShutdown& batteryCausedShutdown) {
1053 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), batteryCausedShutdown);
1054 mProcessor->OnLogEvent(&event);
1055
1056 return hardware::Void();
1057}
1058
David Chen1d7b0cd2017-11-15 14:20:04 -08001059void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001060 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001061 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1062 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001063 ALOGW("Reset statsd upon system server restarts.");
Yangster-mac892f3d32018-05-02 14:16:48 -07001064 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED);
1065 mProcessor->resetConfigs();
1066 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001067 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1068 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
1069 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001070 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001071}
1072
Yao Chenef99c4f2017-09-22 16:26:54 -07001073} // namespace statsd
1074} // namespace os
1075} // namespace android