blob: 0c241fc92d6b550d3a00ad0bf50a3207da1d688f [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>
37#include <utils/Looper.h>
Joe Onorato2cbc2cc2017-08-30 17:03:23 -070038#include <utils/String16.h>
Bookatzb223c4e2018-02-01 15:35:04 -080039#include <statslog.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070040#include <stdio.h>
Yao Chen482d2722017-09-12 13:25:43 -070041#include <stdlib.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070042#include <sys/system_properties.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070043#include <unistd.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070044
45using namespace android;
46
Jeff Sharkey6b649252018-04-16 09:50:22 -060047using android::base::StringPrintf;
48
Bookatz906a35c2017-09-20 15:26:44 -070049namespace android {
50namespace os {
51namespace statsd {
52
David Chenadaf8b32017-11-03 15:42:08 -070053constexpr const char* kPermissionDump = "android.permission.DUMP";
Jeff Sharkey6b649252018-04-16 09:50:22 -060054constexpr const char* kPermissionUsage = "android.permission.PACKAGE_USAGE_STATS";
55
56constexpr const char* kOpUsage = "android:get_usage_stats";
57
yro03faf092017-12-12 00:17:50 -080058#define STATS_SERVICE_DIR "/data/misc/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070059
Jeff Sharkey6b649252018-04-16 09:50:22 -060060static binder::Status ok() {
61 return binder::Status::ok();
62}
63
64static binder::Status exception(uint32_t code, const std::string& msg) {
65 ALOGE("%s (%d)", msg.c_str(), code);
66 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
67}
68
69binder::Status checkUid(uid_t expectedUid) {
70 uid_t uid = IPCThreadState::self()->getCallingUid();
71 if (uid == expectedUid || uid == AID_ROOT) {
72 return ok();
73 } else {
74 return exception(binder::Status::EX_SECURITY,
75 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
76 }
77}
78
79binder::Status checkDumpAndUsageStats(const String16& packageName) {
80 pid_t pid = IPCThreadState::self()->getCallingPid();
81 uid_t uid = IPCThreadState::self()->getCallingUid();
82
83 // Root, system, and shell always have access
84 if (uid == AID_ROOT || uid == AID_SYSTEM || uid == AID_SHELL) {
85 return ok();
86 }
87
88 // Caller must be granted these permissions
89 if (!checkCallingPermission(String16(kPermissionDump))) {
90 return exception(binder::Status::EX_SECURITY,
91 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionDump));
92 }
93 if (!checkCallingPermission(String16(kPermissionUsage))) {
94 return exception(binder::Status::EX_SECURITY,
95 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionUsage));
96 }
97
98 // Caller must also have usage stats op granted
99 PermissionController pc;
100 switch (pc.noteOp(String16(kOpUsage), uid, packageName)) {
101 case PermissionController::MODE_ALLOWED:
102 case PermissionController::MODE_DEFAULT:
103 return ok();
104 default:
105 return exception(binder::Status::EX_SECURITY,
106 StringPrintf("UID %d / PID %d lacks app-op %s", uid, pid, kOpUsage));
107 }
108}
109
110#define ENFORCE_UID(uid) { \
111 binder::Status status = checkUid((uid)); \
112 if (!status.isOk()) { \
113 return status; \
114 } \
115}
116
117#define ENFORCE_DUMP_AND_USAGE_STATS(packageName) { \
118 binder::Status status = checkDumpAndUsageStats(packageName); \
119 if (!status.isOk()) { \
120 return status; \
121 } \
122}
123
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700124StatsService::StatsService(const sp<Looper>& handlerLooper)
Yangster-mac932ecec2018-02-01 10:23:52 -0800125 : mAnomalyAlarmMonitor(new AlarmMonitor(MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
126 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
127 if (sc != nullptr) {
128 sc->setAnomalyAlarm(timeMillis);
129 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
130 }
131 },
132 [](const sp<IStatsCompanionService>& sc) {
133 if (sc != nullptr) {
134 sc->cancelAnomalyAlarm();
135 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
136 }
137 })),
138 mPeriodicAlarmMonitor(new AlarmMonitor(MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
139 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
140 if (sc != nullptr) {
141 sc->setAlarmForSubscriberTriggering(timeMillis);
142 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
143 }
144 },
145 [](const sp<IStatsCompanionService>& sc) {
146 if (sc != nullptr) {
147 sc->cancelAlarmForSubscriberTriggering();
148 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
149 }
150
151 })) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700152 mUidMap = new UidMap();
Chenjie Yue2219202018-06-08 10:07:51 -0700153 mPullerManager = new StatsPullerManager();
Chenjie Yu80f91122018-01-31 20:24:50 -0800154 StatsPuller::SetUidMap(mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700155 mConfigManager = new ConfigManager();
Chenjie Yue2219202018-06-08 10:07:51 -0700156 mProcessor = new StatsLogProcessor(
157 mUidMap, mPullerManager, mAnomalyAlarmMonitor, mPeriodicAlarmMonitor,
158 getElapsedRealtimeNs(), [this](const ConfigKey& key) {
159 sp<IStatsCompanionService> sc = getStatsCompanionService();
160 auto receiver = mConfigManager->GetConfigReceiver(key);
161 if (sc == nullptr) {
162 VLOG("Could not find StatsCompanionService");
163 return false;
164 } else if (receiver == nullptr) {
165 VLOG("Statscompanion could not find a broadcast receiver for %s",
166 key.ToString().c_str());
167 return false;
168 } else {
169 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
170 return true;
171 }
172 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700173
174 mConfigManager->AddListener(mProcessor);
175
176 init_system_properties();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700177}
178
Yao Chenef99c4f2017-09-22 16:26:54 -0700179StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700180}
181
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700182void StatsService::init_system_properties() {
183 mEngBuild = false;
184 const prop_info* buildType = __system_property_find("ro.build.type");
185 if (buildType != NULL) {
186 __system_property_read_callback(buildType, init_build_type_callback, this);
187 }
David Chen0656b7a2017-09-13 15:53:39 -0700188}
189
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700190void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
191 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700192 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700193 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
194 }
195}
196
197/**
198 * Implement our own because the default binder implementation isn't
199 * properly handling SHELL_COMMAND_TRANSACTION.
200 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700201status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
202 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700203 switch (code) {
204 case SHELL_COMMAND_TRANSACTION: {
205 int in = data.readFileDescriptor();
206 int out = data.readFileDescriptor();
207 int err = data.readFileDescriptor();
208 int argc = data.readInt32();
209 Vector<String8> args;
210 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
211 args.add(String8(data.readString16()));
212 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700213 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
214 sp<IResultReceiver> resultReceiver =
215 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700216
217 FILE* fin = fdopen(in, "r");
218 FILE* fout = fdopen(out, "w");
219 FILE* ferr = fdopen(err, "w");
220
221 if (fin == NULL || fout == NULL || ferr == NULL) {
222 resultReceiver->send(NO_MEMORY);
223 } else {
224 err = command(fin, fout, ferr, args);
225 resultReceiver->send(err);
226 }
227
228 if (fin != NULL) {
229 fflush(fin);
230 fclose(fin);
231 }
232 if (fout != NULL) {
233 fflush(fout);
234 fclose(fout);
235 }
236 if (fout != NULL) {
237 fflush(ferr);
238 fclose(ferr);
239 }
240
241 return NO_ERROR;
242 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700243 default: { return BnStatsManager::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700244 }
245}
246
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700247/**
248 * Write debugging data about statsd.
249 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700250status_t StatsService::dump(int fd, const Vector<String16>& args) {
Tej Singhdd83d702018-04-10 17:24:50 -0700251 if (!checkCallingPermission(String16(kPermissionDump))) {
252 return PERMISSION_DENIED;
253 }
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700254 FILE* out = fdopen(fd, "w");
255 if (out == NULL) {
256 return NO_MEMORY; // the fd is already open
257 }
258
Yao Chen884c8c12018-01-26 10:36:25 -0800259 bool verbose = false;
Tej Singh41b3f9a2018-04-03 17:06:35 -0700260 bool proto = false;
Yao Chen884c8c12018-01-26 10:36:25 -0800261 if (args.size() > 0 && !args[0].compare(String16("-v"))) {
262 verbose = true;
263 }
Tej Singh41b3f9a2018-04-03 17:06:35 -0700264 if (args.size() > 0 && !args[args.size()-1].compare(String16("--proto"))) {
265 proto = true;
266 }
Yao Chen884c8c12018-01-26 10:36:25 -0800267
Tej Singh41b3f9a2018-04-03 17:06:35 -0700268 dump_impl(out, verbose, proto);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700269
270 fclose(out);
271 return NO_ERROR;
272}
273
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700274/**
Tej Singh41b3f9a2018-04-03 17:06:35 -0700275 * Write debugging data about statsd in text or proto format.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700276 */
Tej Singh41b3f9a2018-04-03 17:06:35 -0700277void StatsService::dump_impl(FILE* out, bool verbose, bool proto) {
278 if (proto) {
279 vector<uint8_t> data;
280 StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
281 for (size_t i = 0; i < data.size(); i ++) {
282 fprintf(out, "%c", data[i]);
283 }
284 } else {
285 StatsdStats::getInstance().dumpStats(out);
286 mProcessor->dumpStates(out, verbose);
287 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700288}
289
290/**
291 * Implementation of the adb shell cmd stats command.
292 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700293status_t StatsService::command(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600294 uid_t uid = IPCThreadState::self()->getCallingUid();
295 if (uid != AID_ROOT && uid != AID_SHELL) {
296 return PERMISSION_DENIED;
297 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700298
299 const int argCount = args.size();
300 if (argCount >= 1) {
301 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700302 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700303 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700304 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700305
David Chende701692017-10-05 13:16:02 -0700306 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800307 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700308 }
Yao Chen729093d2017-10-16 10:33:26 -0700309
310 if (!args[0].compare(String8("dump-report"))) {
311 return cmd_dump_report(out, err, args);
312 }
David Chen1481fe12017-10-16 13:16:34 -0700313
314 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
315 return cmd_print_pulled_metrics(out, args);
316 }
David Chenadaf8b32017-11-03 15:42:08 -0700317
318 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800319 return cmd_trigger_broadcast(out, args);
320 }
321
322 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800323 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700324 }
yro87d983c2017-11-14 21:31:43 -0800325
Yao Chen8d9989b2017-11-18 18:54:50 -0800326 if (!args[0].compare(String8("meminfo"))) {
327 return cmd_dump_memory_info(out);
328 }
yro947fbce2017-11-15 22:50:23 -0800329
330 if (!args[0].compare(String8("write-to-disk"))) {
331 return cmd_write_data_to_disk(out);
332 }
Bookatzb223c4e2018-02-01 15:35:04 -0800333
David Chen0b5c90c2018-01-25 16:51:49 -0800334 if (!args[0].compare(String8("log-app-breadcrumb"))) {
335 return cmd_log_app_breadcrumb(out, args);
Bookatzb223c4e2018-02-01 15:35:04 -0800336 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800337
338 if (!args[0].compare(String8("clear-puller-cache"))) {
339 return cmd_clear_puller_cache(out);
340 }
Yao Chen876889c2018-05-02 11:16:16 -0700341
342 if (!args[0].compare(String8("print-logs"))) {
343 return cmd_print_logs(out, args);
344 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700345 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700346
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700347 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700348 return NO_ERROR;
349}
350
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700351void StatsService::print_cmd_help(FILE* out) {
352 fprintf(out,
353 "usage: adb shell cmd stats print-stats-log [tag_required] "
354 "[timestamp_nsec_optional]\n");
355 fprintf(out, "\n");
356 fprintf(out, "\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800357 fprintf(out, "usage: adb shell cmd stats meminfo\n");
358 fprintf(out, "\n");
359 fprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
360 fprintf(out, " # adb shell stop\n");
361 fprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
362 fprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
363 fprintf(out, " # adb shell start\n");
364 fprintf(out, "\n");
365 fprintf(out, "\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800366 fprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700367 fprintf(out, "\n");
368 fprintf(out, " Prints the UID, app name, version mapping.\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800369 fprintf(out, " PKG Optional package name to print the uids of the package\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700370 fprintf(out, "\n");
371 fprintf(out, "\n");
yro3fca5ba2017-11-17 13:22:52 -0800372 fprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
David Chen1481fe12017-10-16 13:16:34 -0700373 fprintf(out, "\n");
374 fprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
375 fprintf(out, "\n");
376 fprintf(out, "\n");
yro947fbce2017-11-15 22:50:23 -0800377 fprintf(out, "usage: adb shell cmd stats write-to-disk \n");
378 fprintf(out, "\n");
379 fprintf(out, " Flushes all data on memory to disk.\n");
380 fprintf(out, "\n");
381 fprintf(out, "\n");
David Chen0b5c90c2018-01-25 16:51:49 -0800382 fprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
383 fprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800384 fprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
385 fprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
386 fprintf(out, " uid is used.\n");
387 fprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
388 fprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
389 fprintf(out, "\n");
390 fprintf(out, "\n");
yro74fed972017-11-27 14:42:42 -0800391 fprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700392 fprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
393 fprintf(out, "\n");
394 fprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
yro74fed972017-11-27 14:42:42 -0800395 fprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
396 fprintf(out, " provided, then all configs will be removed from memory and disk.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700397 fprintf(out, "\n");
398 fprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
yro74fed972017-11-27 14:42:42 -0800399 fprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700400 fprintf(out, " uid is used.\n");
401 fprintf(out, " NAME The per-uid name to use\n");
Yao Chen5154a372017-10-30 22:57:06 -0700402 fprintf(out, "\n");
yro74fed972017-11-27 14:42:42 -0800403 fprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
404 fprintf(out, "\n be removed from memory and disk!\n");
Yao Chen5154a372017-10-30 22:57:06 -0700405 fprintf(out, "\n");
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700406 fprintf(out, "usage: adb shell cmd stats dump-report [UID] NAME [--include_current_bucket] [--proto]\n");
Yao Chen5154a372017-10-30 22:57:06 -0700407 fprintf(out, " Dump all metric data for a configuration.\n");
408 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
409 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
410 fprintf(out, " calling uid is used.\n");
411 fprintf(out, " NAME The name of the configuration\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800412 fprintf(out, " --proto Print proto binary.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700413 fprintf(out, "\n");
414 fprintf(out, "\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800415 fprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
416 fprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
417 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
418 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
419 fprintf(out, " calling uid is used.\n");
420 fprintf(out, " NAME The name of the configuration\n");
421 fprintf(out, "\n");
422 fprintf(out, "\n");
Yao Chenf5acabe2018-01-17 14:10:34 -0800423 fprintf(out, "usage: adb shell cmd stats print-stats\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800424 fprintf(out, " Prints some basic stats.\n");
Tej Singh41b3f9a2018-04-03 17:06:35 -0700425 fprintf(out, " --proto Print proto binary instead of string format.\n");
Chenjie Yufa22d652018-02-05 14:37:48 -0800426 fprintf(out, "\n");
427 fprintf(out, "\n");
428 fprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
429 fprintf(out, " Clear cached puller data.\n");
Yao Chen876889c2018-05-02 11:16:16 -0700430 fprintf(out, "\n");
431 fprintf(out, "usage: adb shell cmd stats print-logs\n");
432 fprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700433}
434
David Chen1d7b0cd2017-11-15 14:20:04 -0800435status_t StatsService::cmd_trigger_broadcast(FILE* out, Vector<String8>& args) {
436 string name;
437 bool good = false;
438 int uid;
439 const int argCount = args.size();
440 if (argCount == 2) {
441 // Automatically pick the UID
442 uid = IPCThreadState::self()->getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800443 name.assign(args[1].c_str(), args[1].size());
444 good = true;
445 } else if (argCount == 3) {
446 // If it's a userdebug or eng build, then the shell user can
447 // impersonate other uids.
448 if (mEngBuild) {
449 const char* s = args[1].c_str();
450 if (*s != '\0') {
451 char* end = NULL;
452 uid = strtol(s, &end, 0);
453 if (*end == '\0') {
454 name.assign(args[2].c_str(), args[2].size());
455 good = true;
456 }
457 }
458 } else {
459 fprintf(out,
460 "The metrics can only be dumped for other UIDs on eng or userdebug "
461 "builds.\n");
462 }
463 }
464 if (!good) {
465 print_cmd_help(out);
466 return UNKNOWN_ERROR;
467 }
David Chend37bc232018-04-12 18:05:11 -0700468 ConfigKey key(uid, StrToInt64(name));
469 auto receiver = mConfigManager->GetConfigReceiver(key);
yro4d889e62017-11-17 15:44:48 -0800470 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen661f7912018-01-22 17:46:24 -0800471 if (sc == nullptr) {
472 VLOG("Could not access statsCompanion");
473 } else if (receiver == nullptr) {
474 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str())
475 } else {
David Chend37bc232018-04-12 18:05:11 -0700476 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
yro74fed972017-11-27 14:42:42 -0800477 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
478 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800479 }
480
David Chenadaf8b32017-11-03 15:42:08 -0700481 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700482}
483
484status_t StatsService::cmd_config(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
485 const int argCount = args.size();
486 if (argCount >= 2) {
487 if (args[1] == "update" || args[1] == "remove") {
488 bool good = false;
489 int uid = -1;
490 string name;
491
492 if (argCount == 3) {
493 // Automatically pick the UID
494 uid = IPCThreadState::self()->getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700495 name.assign(args[2].c_str(), args[2].size());
496 good = true;
497 } else if (argCount == 4) {
498 // If it's a userdebug or eng build, then the shell user can
499 // impersonate other uids.
500 if (mEngBuild) {
501 const char* s = args[2].c_str();
502 if (*s != '\0') {
503 char* end = NULL;
504 uid = strtol(s, &end, 0);
505 if (*end == '\0') {
506 name.assign(args[3].c_str(), args[3].size());
507 good = true;
508 }
509 }
510 } else {
Yao Chen729093d2017-10-16 10:33:26 -0700511 fprintf(err,
512 "The config can only be set for other UIDs on eng or userdebug "
513 "builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700514 }
yroe5f82922018-01-22 18:37:27 -0800515 } else if (argCount == 2 && args[1] == "remove") {
516 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700517 }
518
519 if (!good) {
520 // If arg parsing failed, print the help text and return an error.
521 print_cmd_help(out);
522 return UNKNOWN_ERROR;
523 }
524
525 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800526 char* endp;
527 int64_t configID = strtoll(name.c_str(), &endp, 10);
528 if (endp == name.c_str() || *endp != '\0') {
529 fprintf(err, "Error parsing config ID.\n");
530 return UNKNOWN_ERROR;
531 }
532
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700533 // Read stream into buffer.
534 string buffer;
535 if (!android::base::ReadFdToString(fileno(in), &buffer)) {
536 fprintf(err, "Error reading stream for StatsConfig.\n");
537 return UNKNOWN_ERROR;
538 }
539
540 // Parse buffer.
541 StatsdConfig config;
542 if (!config.ParseFromString(buffer)) {
543 fprintf(err, "Error parsing proto stream for StatsConfig.\n");
544 return UNKNOWN_ERROR;
545 }
546
547 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800548 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700549 } else {
yro74fed972017-11-27 14:42:42 -0800550 if (argCount == 2) {
551 cmd_remove_all_configs(out);
552 } else {
553 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800554 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800555 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700556 }
557
558 return NO_ERROR;
559 }
David Chen0656b7a2017-09-13 15:53:39 -0700560 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700561 print_cmd_help(out);
562 return UNKNOWN_ERROR;
563}
564
Yao Chen729093d2017-10-16 10:33:26 -0700565status_t StatsService::cmd_dump_report(FILE* out, FILE* err, const Vector<String8>& args) {
566 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800567 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700568 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800569 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700570 bool includeCurrentBucket = false;
Yao Chen729093d2017-10-16 10:33:26 -0700571 int uid;
572 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800573 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
574 proto = true;
575 argCount -= 1;
576 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700577 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
578 includeCurrentBucket = true;
579 argCount -= 1;
580 }
Yao Chen729093d2017-10-16 10:33:26 -0700581 if (argCount == 2) {
582 // Automatically pick the UID
583 uid = IPCThreadState::self()->getCallingUid();
Yao Chen5154a372017-10-30 22:57:06 -0700584 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700585 good = true;
586 } else if (argCount == 3) {
587 // If it's a userdebug or eng build, then the shell user can
588 // impersonate other uids.
589 if (mEngBuild) {
590 const char* s = args[1].c_str();
591 if (*s != '\0') {
592 char* end = NULL;
593 uid = strtol(s, &end, 0);
594 if (*end == '\0') {
595 name.assign(args[2].c_str(), args[2].size());
596 good = true;
597 }
598 }
599 } else {
600 fprintf(out,
601 "The metrics can only be dumped for other UIDs on eng or userdebug "
602 "builds.\n");
603 }
604 }
605 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800606 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800607 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700608 includeCurrentBucket, ADB_DUMP, &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800609 if (proto) {
610 for (size_t i = 0; i < data.size(); i ++) {
611 fprintf(out, "%c", data[i]);
612 }
613 } else {
614 fprintf(out, "Dump report for Config [%d,%s]\n", uid, name.c_str());
615 fprintf(out, "See the StatsLogReport in logcat...\n");
616 }
Yao Chen729093d2017-10-16 10:33:26 -0700617 return android::OK;
618 } else {
619 // If arg parsing failed, print the help text and return an error.
620 print_cmd_help(out);
621 return UNKNOWN_ERROR;
622 }
623 } else {
624 fprintf(out, "Log processor does not exist...\n");
625 return UNKNOWN_ERROR;
626 }
627}
628
Yao Chenb3561512017-11-21 18:07:17 -0800629status_t StatsService::cmd_print_stats(FILE* out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700630 int argCount = args.size();
631 bool proto = false;
632 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
633 proto = true;
634 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800635 }
Yao Chenb3561512017-11-21 18:07:17 -0800636 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700637 if (proto) {
638 vector<uint8_t> data;
639 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
640 for (size_t i = 0; i < data.size(); i ++) {
641 fprintf(out, "%c", data[i]);
642 }
643
644 } else {
645 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
646 for (const ConfigKey& key : configs) {
647 fprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
648 mProcessor->GetMetricsSize(key));
649 }
650 statsdStats.dumpStats(out);
651 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800652 return NO_ERROR;
653}
654
Yao Chend10f7b12017-12-18 12:53:50 -0800655status_t StatsService::cmd_print_uid_map(FILE* out, const Vector<String8>& args) {
656 if (args.size() > 1) {
657 string pkg;
658 pkg.assign(args[1].c_str(), args[1].size());
659 auto uids = mUidMap->getAppUid(pkg);
660 fprintf(out, "%s -> [ ", pkg.c_str());
661 for (const auto& uid : uids) {
662 fprintf(out, "%d ", uid);
663 }
664 fprintf(out, "]\n");
665 } else {
666 mUidMap->printUidMap(out);
667 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700668 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700669}
670
yro947fbce2017-11-15 22:50:23 -0800671status_t StatsService::cmd_write_data_to_disk(FILE* out) {
672 fprintf(out, "Writing data to disk\n");
Yangster-mac892f3d32018-05-02 14:16:48 -0700673 mProcessor->WriteDataToDisk(ADB_DUMP);
yro947fbce2017-11-15 22:50:23 -0800674 return NO_ERROR;
675}
676
David Chen0b5c90c2018-01-25 16:51:49 -0800677status_t StatsService::cmd_log_app_breadcrumb(FILE* out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800678 bool good = false;
679 int32_t uid;
680 int32_t label;
681 int32_t state;
682 const int argCount = args.size();
683 if (argCount == 3) {
684 // Automatically pick the UID
685 uid = IPCThreadState::self()->getCallingUid();
686 label = atoi(args[1].c_str());
687 state = atoi(args[2].c_str());
688 good = true;
689 } else if (argCount == 4) {
690 uid = atoi(args[1].c_str());
691 // If it's a userdebug or eng build, then the shell user can impersonate other uids.
692 // Otherwise, the uid must match the actual caller's uid.
693 if (mEngBuild || (uid >= 0 && (uid_t)uid == IPCThreadState::self()->getCallingUid())) {
694 label = atoi(args[2].c_str());
695 state = atoi(args[3].c_str());
696 good = true;
697 } else {
698 fprintf(out,
David Chenb639d142018-02-14 17:29:54 -0800699 "Selecting a UID for writing AppBreadcrumb can only be done for other UIDs "
700 "on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800701 }
702 }
703 if (good) {
David Chen0b5c90c2018-01-25 16:51:49 -0800704 fprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
705 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800706 } else {
707 print_cmd_help(out);
708 return UNKNOWN_ERROR;
709 }
710 return NO_ERROR;
711}
712
David Chen1481fe12017-10-16 13:16:34 -0700713status_t StatsService::cmd_print_pulled_metrics(FILE* out, const Vector<String8>& args) {
714 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700715 vector<shared_ptr<LogEvent> > stats;
Chenjie Yue2219202018-06-08 10:07:51 -0700716 if (mPullerManager->Pull(s, getElapsedRealtimeNs(), &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700717 for (const auto& it : stats) {
718 fprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
719 }
720 fprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
721 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700722 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700723 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700724}
725
yro74fed972017-11-27 14:42:42 -0800726status_t StatsService::cmd_remove_all_configs(FILE* out) {
727 fprintf(out, "Removing all configs...\n");
728 VLOG("StatsService::cmd_remove_all_configs was called");
729 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800730 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800731 return NO_ERROR;
732}
733
Yao Chen8d9989b2017-11-18 18:54:50 -0800734status_t StatsService::cmd_dump_memory_info(FILE* out) {
Yao Chen20e9e622018-02-28 11:18:51 -0800735 fprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800736 return NO_ERROR;
737}
738
Chenjie Yue72252b2018-02-01 13:19:35 -0800739status_t StatsService::cmd_clear_puller_cache(FILE* out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800740 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800741 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
742 ipc->getCallingPid(), ipc->getCallingUid());
Chenjie Yufa22d652018-02-05 14:37:48 -0800743 if (checkCallingPermission(String16(kPermissionDump))) {
Chenjie Yue2219202018-06-08 10:07:51 -0700744 int cleared = mPullerManager->ForceClearPullerCache();
Chenjie Yufa22d652018-02-05 14:37:48 -0800745 fprintf(out, "Puller removed %d cached data!\n", cleared);
746 return NO_ERROR;
747 } else {
748 return PERMISSION_DENIED;
749 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800750}
751
Yao Chen876889c2018-05-02 11:16:16 -0700752status_t StatsService::cmd_print_logs(FILE* out, const Vector<String8>& args) {
753 IPCThreadState* ipc = IPCThreadState::self();
754 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", ipc->getCallingPid(),
755 ipc->getCallingUid());
756 if (checkCallingPermission(String16(kPermissionDump))) {
757 bool enabled = true;
758 if (args.size() >= 2) {
759 enabled = atoi(args[1].c_str()) != 0;
760 }
761 mProcessor->setPrintLogs(enabled);
762 return NO_ERROR;
763 } else {
764 return PERMISSION_DENIED;
765 }
766}
767
Dianne Hackborn3accca02013-09-20 09:32:11 -0700768Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int64_t>& version,
David Chende701692017-10-05 13:16:02 -0700769 const vector<String16>& app) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600770 ENFORCE_UID(AID_SYSTEM);
771
yro74fed972017-11-27 14:42:42 -0800772 VLOG("StatsService::informAllUidData was called");
David Chenbd125272018-04-04 19:02:50 -0700773 mUidMap->updateMap(getElapsedRealtimeNs(), uid, version, app);
yro74fed972017-11-27 14:42:42 -0800774 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700775
776 return Status::ok();
777}
778
Dianne Hackborn3accca02013-09-20 09:32:11 -0700779Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600780 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700781
Jeff Sharkey6b649252018-04-16 09:50:22 -0600782 VLOG("StatsService::informOnePackage was called");
David Chenbd125272018-04-04 19:02:50 -0700783 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version);
David Chende701692017-10-05 13:16:02 -0700784 return Status::ok();
785}
786
787Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600788 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700789
Jeff Sharkey6b649252018-04-16 09:50:22 -0600790 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -0700791 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -0800792 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -0700793 return Status::ok();
794}
795
Yao Chenef99c4f2017-09-22 16:26:54 -0700796Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600797 ENFORCE_UID(AID_SYSTEM);
798
yro74fed972017-11-27 14:42:42 -0800799 VLOG("StatsService::informAnomalyAlarmFired 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 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
803 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -0800804 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -0800805 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -0800806 } else {
807 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
808 }
Bookatz1b0b1142017-09-08 11:58:42 -0700809 return Status::ok();
810}
811
Yangster-mac932ecec2018-02-01 10:23:52 -0800812Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600813 ENFORCE_UID(AID_SYSTEM);
814
Yangster-mac932ecec2018-02-01 10:23:52 -0800815 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700816 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800817 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
818 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
819 if (alarmSet.size() > 0) {
820 VLOG("Found periodic alarm fired.");
821 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
822 } else {
823 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
824 }
825 return Status::ok();
826}
827
Yao Chenef99c4f2017-09-22 16:26:54 -0700828Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600829 ENFORCE_UID(AID_SYSTEM);
830
yro74fed972017-11-27 14:42:42 -0800831 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700832 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -0800833 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700834 return Status::ok();
835}
836
Yao Chenef99c4f2017-09-22 16:26:54 -0700837Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600838 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700839
840 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800841 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -0700842 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700843 return Status::ok();
844}
845
Yangster-mac892f3d32018-05-02 14:16:48 -0700846Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600847 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -0700848 VLOG("StatsService::informDeviceShutdown");
Yangster-mac892f3d32018-05-02 14:16:48 -0700849 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN);
yro947fbce2017-11-15 22:50:23 -0800850 return Status::ok();
851}
852
Yao Chenef99c4f2017-09-22 16:26:54 -0700853void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -0700854 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
855 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -0800856 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -0700857 statsCompanion->statsdReady();
858 } else {
yro74fed972017-11-27 14:42:42 -0800859 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -0700860 }
861}
862
Yao Chenef99c4f2017-09-22 16:26:54 -0700863Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600864 ENFORCE_UID(AID_SYSTEM);
865
yro74fed972017-11-27 14:42:42 -0800866 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -0700867 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
868 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700869 return Status::fromExceptionCode(
870 Status::EX_NULL_POINTER,
871 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700872 }
yro74fed972017-11-27 14:42:42 -0800873 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -0700874 IInterface::asBinder(statsCompanion)->linkToDeath(this);
Chenjie Yue2219202018-06-08 10:07:51 -0700875 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -0800876 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
877 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -0800878 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -0700879 return Status::ok();
880}
881
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700882void StatsService::Startup() {
883 mConfigManager->Startup();
Bookatz906a35c2017-09-20 15:26:44 -0700884}
885
Yao Chen163d2602018-04-10 10:39:53 -0700886void StatsService::OnLogEvent(LogEvent* event, bool reconnectionStarts) {
887 mProcessor->OnLogEvent(event, reconnectionStarts);
Bookatz906a35c2017-09-20 15:26:44 -0700888}
889
Jeff Sharkey6b649252018-04-16 09:50:22 -0600890Status StatsService::getData(int64_t key, const String16& packageName, vector<uint8_t>* output) {
891 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
892
David Chenadaf8b32017-11-03 15:42:08 -0700893 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -0800894 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -0700895 ConfigKey configKey(ipc->getCallingUid(), key);
David Chen56ae0d92018-05-11 16:00:22 -0700896 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
897 GET_DATA_CALLED, output);
Bookatz4f716292018-04-10 17:15:12 -0700898 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700899}
900
Jeff Sharkey6b649252018-04-16 09:50:22 -0600901Status StatsService::getMetadata(const String16& packageName, vector<uint8_t>* output) {
902 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
903
David Chen2e8f3802017-11-22 10:56:48 -0800904 IPCThreadState* ipc = IPCThreadState::self();
905 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
906 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -0700907 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
908 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -0800909}
910
Jeff Sharkey6b649252018-04-16 09:50:22 -0600911Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
912 const String16& packageName) {
913 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
914
David Chenadaf8b32017-11-03 15:42:08 -0700915 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -0700916 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -0800917 return Status::ok();
918 } else {
Bookatz4f716292018-04-10 17:15:12 -0700919 ALOGE("Could not parse malformatted StatsdConfig");
920 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
921 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -0800922 }
923}
924
David Chen9fdd4032018-03-20 14:38:56 -0700925bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
926 ConfigKey configKey(uid, key);
927 StatsdConfig cfg;
928 if (config.size() > 0) { // If the config is empty, skip parsing.
929 if (!cfg.ParseFromArray(&config[0], config.size())) {
930 return false;
931 }
932 }
933 mConfigManager->UpdateConfig(configKey, cfg);
934 return true;
935}
936
Jeff Sharkey6b649252018-04-16 09:50:22 -0600937Status StatsService::removeDataFetchOperation(int64_t key, const String16& packageName) {
938 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
939
Bookatz4f716292018-04-10 17:15:12 -0700940 IPCThreadState* ipc = IPCThreadState::self();
941 ConfigKey configKey(ipc->getCallingUid(), key);
942 mConfigManager->RemoveConfigReceiver(configKey);
943 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -0800944}
945
Jeff Sharkey6b649252018-04-16 09:50:22 -0600946Status StatsService::setDataFetchOperation(int64_t key,
947 const sp<android::IBinder>& intentSender,
948 const String16& packageName) {
949 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
950
Bookatz4f716292018-04-10 17:15:12 -0700951 IPCThreadState* ipc = IPCThreadState::self();
952 ConfigKey configKey(ipc->getCallingUid(), key);
953 mConfigManager->SetConfigReceiver(configKey, intentSender);
David Chen48944902018-05-03 10:29:11 -0700954 if (StorageManager::hasConfigMetricsReport(configKey)) {
955 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
956 configKey.ToString().c_str());
957 mProcessor->noteOnDiskData(configKey);
958 }
Bookatz4f716292018-04-10 17:15:12 -0700959 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700960}
961
Jeff Sharkey6b649252018-04-16 09:50:22 -0600962Status StatsService::removeConfiguration(int64_t key, const String16& packageName) {
963 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
964
Bookatz4f716292018-04-10 17:15:12 -0700965 IPCThreadState* ipc = IPCThreadState::self();
966 ConfigKey configKey(ipc->getCallingUid(), key);
967 mConfigManager->RemoveConfig(configKey);
968 SubscriberReporter::getInstance().removeConfig(configKey);
969 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700970}
971
Bookatzc6977972018-01-16 16:55:05 -0800972Status StatsService::setBroadcastSubscriber(int64_t configId,
973 int64_t subscriberId,
Jeff Sharkey6b649252018-04-16 09:50:22 -0600974 const sp<android::IBinder>& intentSender,
975 const String16& packageName) {
976 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
977
Bookatzc6977972018-01-16 16:55:05 -0800978 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -0700979 IPCThreadState* ipc = IPCThreadState::self();
980 ConfigKey configKey(ipc->getCallingUid(), configId);
981 SubscriberReporter::getInstance()
982 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
983 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -0800984}
985
986Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -0600987 int64_t subscriberId,
988 const String16& packageName) {
989 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
990
Bookatzc6977972018-01-16 16:55:05 -0800991 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -0700992 IPCThreadState* ipc = IPCThreadState::self();
993 ConfigKey configKey(ipc->getCallingUid(), configId);
994 SubscriberReporter::getInstance()
995 .unsetBroadcastSubscriber(configKey, subscriberId);
996 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -0800997}
998
yrobe6d7f92018-05-04 13:02:53 -0700999Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
1000 // Permission check not necessary as it's meant for applications to write to
1001 // statsd.
1002 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
1003 IPCThreadState::self()->getCallingUid(), label,
1004 state);
1005 return Status::ok();
1006}
1007
David Chen1d7b0cd2017-11-15 14:20:04 -08001008void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001009 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001010 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1011 if (mProcessor != nullptr) {
1012 ALOGW("Reset statsd upon system server restars.");
1013 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED);
1014 mProcessor->resetConfigs();
1015 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001016 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1017 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
1018 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001019 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001020}
1021
Yao Chenef99c4f2017-09-22 16:26:54 -07001022} // namespace statsd
1023} // namespace os
1024} // namespace android