blob: 811edb5909a51fb076b73b47af414fa37e5f89d5 [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 Yu80f91122018-01-31 20:24:50 -0800153 StatsPuller::SetUidMap(mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700154 mConfigManager = new ConfigManager();
Yangster-mac932ecec2018-02-01 10:23:52 -0800155 mProcessor = new StatsLogProcessor(mUidMap, mAnomalyAlarmMonitor, mPeriodicAlarmMonitor,
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700156 getElapsedRealtimeNs(), [this](const ConfigKey& key) {
Yangster-mac932ecec2018-02-01 10:23:52 -0800157 sp<IStatsCompanionService> sc = getStatsCompanionService();
158 auto receiver = mConfigManager->GetConfigReceiver(key);
159 if (sc == nullptr) {
160 VLOG("Could not find StatsCompanionService");
161 } else if (receiver == nullptr) {
162 VLOG("Statscompanion could not find a broadcast receiver for %s",
163 key.ToString().c_str());
164 } else {
David Chend37bc232018-04-12 18:05:11 -0700165 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
David Chen1d7b0cd2017-11-15 14:20:04 -0800166 }
Yangster-mac932ecec2018-02-01 10:23:52 -0800167 }
Yangster-mac330af582018-02-08 15:24:38 -0800168 );
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700169
170 mConfigManager->AddListener(mProcessor);
171
172 init_system_properties();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700173}
174
Yao Chenef99c4f2017-09-22 16:26:54 -0700175StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700176}
177
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700178void StatsService::init_system_properties() {
179 mEngBuild = false;
180 const prop_info* buildType = __system_property_find("ro.build.type");
181 if (buildType != NULL) {
182 __system_property_read_callback(buildType, init_build_type_callback, this);
183 }
David Chen0656b7a2017-09-13 15:53:39 -0700184}
185
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700186void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
187 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700188 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700189 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
190 }
191}
192
193/**
194 * Implement our own because the default binder implementation isn't
195 * properly handling SHELL_COMMAND_TRANSACTION.
196 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700197status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
198 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700199 switch (code) {
200 case SHELL_COMMAND_TRANSACTION: {
201 int in = data.readFileDescriptor();
202 int out = data.readFileDescriptor();
203 int err = data.readFileDescriptor();
204 int argc = data.readInt32();
205 Vector<String8> args;
206 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
207 args.add(String8(data.readString16()));
208 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700209 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
210 sp<IResultReceiver> resultReceiver =
211 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700212
213 FILE* fin = fdopen(in, "r");
214 FILE* fout = fdopen(out, "w");
215 FILE* ferr = fdopen(err, "w");
216
217 if (fin == NULL || fout == NULL || ferr == NULL) {
218 resultReceiver->send(NO_MEMORY);
219 } else {
220 err = command(fin, fout, ferr, args);
221 resultReceiver->send(err);
222 }
223
224 if (fin != NULL) {
225 fflush(fin);
226 fclose(fin);
227 }
228 if (fout != NULL) {
229 fflush(fout);
230 fclose(fout);
231 }
232 if (fout != NULL) {
233 fflush(ferr);
234 fclose(ferr);
235 }
236
237 return NO_ERROR;
238 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700239 default: { return BnStatsManager::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700240 }
241}
242
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700243/**
244 * Write debugging data about statsd.
245 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700246status_t StatsService::dump(int fd, const Vector<String16>& args) {
Tej Singhdd83d702018-04-10 17:24:50 -0700247 if (!checkCallingPermission(String16(kPermissionDump))) {
248 return PERMISSION_DENIED;
249 }
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700250 FILE* out = fdopen(fd, "w");
251 if (out == NULL) {
252 return NO_MEMORY; // the fd is already open
253 }
254
Yao Chen884c8c12018-01-26 10:36:25 -0800255 bool verbose = false;
Tej Singh41b3f9a2018-04-03 17:06:35 -0700256 bool proto = false;
Yao Chen884c8c12018-01-26 10:36:25 -0800257 if (args.size() > 0 && !args[0].compare(String16("-v"))) {
258 verbose = true;
259 }
Tej Singh41b3f9a2018-04-03 17:06:35 -0700260 if (args.size() > 0 && !args[args.size()-1].compare(String16("--proto"))) {
261 proto = true;
262 }
Yao Chen884c8c12018-01-26 10:36:25 -0800263
Tej Singh41b3f9a2018-04-03 17:06:35 -0700264 dump_impl(out, verbose, proto);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700265
266 fclose(out);
267 return NO_ERROR;
268}
269
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700270/**
Tej Singh41b3f9a2018-04-03 17:06:35 -0700271 * Write debugging data about statsd in text or proto format.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700272 */
Tej Singh41b3f9a2018-04-03 17:06:35 -0700273void StatsService::dump_impl(FILE* out, bool verbose, bool proto) {
274 if (proto) {
275 vector<uint8_t> data;
276 StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
277 for (size_t i = 0; i < data.size(); i ++) {
278 fprintf(out, "%c", data[i]);
279 }
280 } else {
281 StatsdStats::getInstance().dumpStats(out);
282 mProcessor->dumpStates(out, verbose);
283 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700284}
285
286/**
287 * Implementation of the adb shell cmd stats command.
288 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700289status_t StatsService::command(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600290 uid_t uid = IPCThreadState::self()->getCallingUid();
291 if (uid != AID_ROOT && uid != AID_SHELL) {
292 return PERMISSION_DENIED;
293 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700294
295 const int argCount = args.size();
296 if (argCount >= 1) {
297 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700298 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700299 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700300 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700301
David Chende701692017-10-05 13:16:02 -0700302 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800303 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700304 }
Yao Chen729093d2017-10-16 10:33:26 -0700305
306 if (!args[0].compare(String8("dump-report"))) {
307 return cmd_dump_report(out, err, args);
308 }
David Chen1481fe12017-10-16 13:16:34 -0700309
310 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
311 return cmd_print_pulled_metrics(out, args);
312 }
David Chenadaf8b32017-11-03 15:42:08 -0700313
314 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800315 return cmd_trigger_broadcast(out, args);
316 }
317
318 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800319 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700320 }
yro87d983c2017-11-14 21:31:43 -0800321
Yao Chen8d9989b2017-11-18 18:54:50 -0800322 if (!args[0].compare(String8("meminfo"))) {
323 return cmd_dump_memory_info(out);
324 }
yro947fbce2017-11-15 22:50:23 -0800325
326 if (!args[0].compare(String8("write-to-disk"))) {
327 return cmd_write_data_to_disk(out);
328 }
Bookatzb223c4e2018-02-01 15:35:04 -0800329
David Chen0b5c90c2018-01-25 16:51:49 -0800330 if (!args[0].compare(String8("log-app-breadcrumb"))) {
331 return cmd_log_app_breadcrumb(out, args);
Bookatzb223c4e2018-02-01 15:35:04 -0800332 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800333
334 if (!args[0].compare(String8("clear-puller-cache"))) {
335 return cmd_clear_puller_cache(out);
336 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700337 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700338
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700339 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700340 return NO_ERROR;
341}
342
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700343void StatsService::print_cmd_help(FILE* out) {
344 fprintf(out,
345 "usage: adb shell cmd stats print-stats-log [tag_required] "
346 "[timestamp_nsec_optional]\n");
347 fprintf(out, "\n");
348 fprintf(out, "\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800349 fprintf(out, "usage: adb shell cmd stats meminfo\n");
350 fprintf(out, "\n");
351 fprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
352 fprintf(out, " # adb shell stop\n");
353 fprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
354 fprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
355 fprintf(out, " # adb shell start\n");
356 fprintf(out, "\n");
357 fprintf(out, "\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800358 fprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700359 fprintf(out, "\n");
360 fprintf(out, " Prints the UID, app name, version mapping.\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800361 fprintf(out, " PKG Optional package name to print the uids of the package\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700362 fprintf(out, "\n");
363 fprintf(out, "\n");
yro3fca5ba2017-11-17 13:22:52 -0800364 fprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
David Chen1481fe12017-10-16 13:16:34 -0700365 fprintf(out, "\n");
366 fprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
367 fprintf(out, "\n");
368 fprintf(out, "\n");
yro947fbce2017-11-15 22:50:23 -0800369 fprintf(out, "usage: adb shell cmd stats write-to-disk \n");
370 fprintf(out, "\n");
371 fprintf(out, " Flushes all data on memory to disk.\n");
372 fprintf(out, "\n");
373 fprintf(out, "\n");
David Chen0b5c90c2018-01-25 16:51:49 -0800374 fprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
375 fprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800376 fprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
377 fprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
378 fprintf(out, " uid is used.\n");
379 fprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
380 fprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
381 fprintf(out, "\n");
382 fprintf(out, "\n");
yro74fed972017-11-27 14:42:42 -0800383 fprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700384 fprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
385 fprintf(out, "\n");
386 fprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
yro74fed972017-11-27 14:42:42 -0800387 fprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
388 fprintf(out, " provided, then all configs will be removed from memory and disk.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700389 fprintf(out, "\n");
390 fprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
yro74fed972017-11-27 14:42:42 -0800391 fprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700392 fprintf(out, " uid is used.\n");
393 fprintf(out, " NAME The per-uid name to use\n");
Yao Chen5154a372017-10-30 22:57:06 -0700394 fprintf(out, "\n");
yro74fed972017-11-27 14:42:42 -0800395 fprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
396 fprintf(out, "\n be removed from memory and disk!\n");
Yao Chen5154a372017-10-30 22:57:06 -0700397 fprintf(out, "\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800398 fprintf(out, "usage: adb shell cmd stats dump-report [UID] NAME [--proto]\n");
Yao Chen5154a372017-10-30 22:57:06 -0700399 fprintf(out, " Dump all metric data for a configuration.\n");
400 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
401 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
402 fprintf(out, " calling uid is used.\n");
403 fprintf(out, " NAME The name of the configuration\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800404 fprintf(out, " --proto Print proto binary.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700405 fprintf(out, "\n");
406 fprintf(out, "\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800407 fprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
408 fprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
409 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
410 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
411 fprintf(out, " calling uid is used.\n");
412 fprintf(out, " NAME The name of the configuration\n");
413 fprintf(out, "\n");
414 fprintf(out, "\n");
Yao Chenf5acabe2018-01-17 14:10:34 -0800415 fprintf(out, "usage: adb shell cmd stats print-stats\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800416 fprintf(out, " Prints some basic stats.\n");
Tej Singh41b3f9a2018-04-03 17:06:35 -0700417 fprintf(out, " --proto Print proto binary instead of string format.\n");
Chenjie Yufa22d652018-02-05 14:37:48 -0800418 fprintf(out, "\n");
419 fprintf(out, "\n");
420 fprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
421 fprintf(out, " Clear cached puller data.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700422}
423
David Chen1d7b0cd2017-11-15 14:20:04 -0800424status_t StatsService::cmd_trigger_broadcast(FILE* out, Vector<String8>& args) {
425 string name;
426 bool good = false;
427 int uid;
428 const int argCount = args.size();
429 if (argCount == 2) {
430 // Automatically pick the UID
431 uid = IPCThreadState::self()->getCallingUid();
432 // TODO: What if this isn't a binder call? Should we fail?
433 name.assign(args[1].c_str(), args[1].size());
434 good = true;
435 } else if (argCount == 3) {
436 // If it's a userdebug or eng build, then the shell user can
437 // impersonate other uids.
438 if (mEngBuild) {
439 const char* s = args[1].c_str();
440 if (*s != '\0') {
441 char* end = NULL;
442 uid = strtol(s, &end, 0);
443 if (*end == '\0') {
444 name.assign(args[2].c_str(), args[2].size());
445 good = true;
446 }
447 }
448 } else {
449 fprintf(out,
450 "The metrics can only be dumped for other UIDs on eng or userdebug "
451 "builds.\n");
452 }
453 }
454 if (!good) {
455 print_cmd_help(out);
456 return UNKNOWN_ERROR;
457 }
David Chend37bc232018-04-12 18:05:11 -0700458 ConfigKey key(uid, StrToInt64(name));
459 auto receiver = mConfigManager->GetConfigReceiver(key);
yro4d889e62017-11-17 15:44:48 -0800460 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen661f7912018-01-22 17:46:24 -0800461 if (sc == nullptr) {
462 VLOG("Could not access statsCompanion");
463 } else if (receiver == nullptr) {
464 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str())
465 } else {
David Chend37bc232018-04-12 18:05:11 -0700466 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
yro74fed972017-11-27 14:42:42 -0800467 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
468 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800469 }
470
David Chenadaf8b32017-11-03 15:42:08 -0700471 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700472}
473
474status_t StatsService::cmd_config(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
475 const int argCount = args.size();
476 if (argCount >= 2) {
477 if (args[1] == "update" || args[1] == "remove") {
478 bool good = false;
479 int uid = -1;
480 string name;
481
482 if (argCount == 3) {
483 // Automatically pick the UID
484 uid = IPCThreadState::self()->getCallingUid();
485 // TODO: What if this isn't a binder call? Should we fail?
486 name.assign(args[2].c_str(), args[2].size());
487 good = true;
488 } else if (argCount == 4) {
489 // If it's a userdebug or eng build, then the shell user can
490 // impersonate other uids.
491 if (mEngBuild) {
492 const char* s = args[2].c_str();
493 if (*s != '\0') {
494 char* end = NULL;
495 uid = strtol(s, &end, 0);
496 if (*end == '\0') {
497 name.assign(args[3].c_str(), args[3].size());
498 good = true;
499 }
500 }
501 } else {
Yao Chen729093d2017-10-16 10:33:26 -0700502 fprintf(err,
503 "The config can only be set for other UIDs on eng or userdebug "
504 "builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700505 }
yroe5f82922018-01-22 18:37:27 -0800506 } else if (argCount == 2 && args[1] == "remove") {
507 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700508 }
509
510 if (!good) {
511 // If arg parsing failed, print the help text and return an error.
512 print_cmd_help(out);
513 return UNKNOWN_ERROR;
514 }
515
516 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800517 char* endp;
518 int64_t configID = strtoll(name.c_str(), &endp, 10);
519 if (endp == name.c_str() || *endp != '\0') {
520 fprintf(err, "Error parsing config ID.\n");
521 return UNKNOWN_ERROR;
522 }
523
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700524 // Read stream into buffer.
525 string buffer;
526 if (!android::base::ReadFdToString(fileno(in), &buffer)) {
527 fprintf(err, "Error reading stream for StatsConfig.\n");
528 return UNKNOWN_ERROR;
529 }
530
531 // Parse buffer.
532 StatsdConfig config;
533 if (!config.ParseFromString(buffer)) {
534 fprintf(err, "Error parsing proto stream for StatsConfig.\n");
535 return UNKNOWN_ERROR;
536 }
537
538 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800539 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700540 } else {
yro74fed972017-11-27 14:42:42 -0800541 if (argCount == 2) {
542 cmd_remove_all_configs(out);
543 } else {
544 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800545 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800546 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700547 }
548
549 return NO_ERROR;
550 }
David Chen0656b7a2017-09-13 15:53:39 -0700551 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700552 print_cmd_help(out);
553 return UNKNOWN_ERROR;
554}
555
Yao Chen729093d2017-10-16 10:33:26 -0700556status_t StatsService::cmd_dump_report(FILE* out, FILE* err, const Vector<String8>& args) {
557 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800558 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700559 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800560 bool proto = false;
Yao Chen729093d2017-10-16 10:33:26 -0700561 int uid;
562 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800563 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
564 proto = true;
565 argCount -= 1;
566 }
Yao Chen729093d2017-10-16 10:33:26 -0700567 if (argCount == 2) {
568 // Automatically pick the UID
569 uid = IPCThreadState::self()->getCallingUid();
570 // TODO: What if this isn't a binder call? Should we fail?
Yao Chen5154a372017-10-30 22:57:06 -0700571 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700572 good = true;
573 } else if (argCount == 3) {
574 // If it's a userdebug or eng build, then the shell user can
575 // impersonate other uids.
576 if (mEngBuild) {
577 const char* s = args[1].c_str();
578 if (*s != '\0') {
579 char* end = NULL;
580 uid = strtol(s, &end, 0);
581 if (*end == '\0') {
582 name.assign(args[2].c_str(), args[2].size());
583 good = true;
584 }
585 }
586 } else {
587 fprintf(out,
588 "The metrics can only be dumped for other UIDs on eng or userdebug "
589 "builds.\n");
590 }
591 }
592 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800593 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800594 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Yangster-mac9def8e32018-04-17 13:55:51 -0700595 false /* include_current_bucket*/,
596 true /* include strings */, ADB_DUMP, &data);
Yao Chen729093d2017-10-16 10:33:26 -0700597 // TODO: print the returned StatsLogReport to file instead of printing to logcat.
Chenjie Yub236c862017-11-28 22:20:44 -0800598 if (proto) {
599 for (size_t i = 0; i < data.size(); i ++) {
600 fprintf(out, "%c", data[i]);
601 }
602 } else {
603 fprintf(out, "Dump report for Config [%d,%s]\n", uid, name.c_str());
604 fprintf(out, "See the StatsLogReport in logcat...\n");
605 }
Yao Chen729093d2017-10-16 10:33:26 -0700606 return android::OK;
607 } else {
608 // If arg parsing failed, print the help text and return an error.
609 print_cmd_help(out);
610 return UNKNOWN_ERROR;
611 }
612 } else {
613 fprintf(out, "Log processor does not exist...\n");
614 return UNKNOWN_ERROR;
615 }
616}
617
Yao Chenb3561512017-11-21 18:07:17 -0800618status_t StatsService::cmd_print_stats(FILE* out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700619 int argCount = args.size();
620 bool proto = false;
621 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
622 proto = true;
623 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800624 }
Yao Chenb3561512017-11-21 18:07:17 -0800625 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700626 if (proto) {
627 vector<uint8_t> data;
628 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
629 for (size_t i = 0; i < data.size(); i ++) {
630 fprintf(out, "%c", data[i]);
631 }
632
633 } else {
634 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
635 for (const ConfigKey& key : configs) {
636 fprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
637 mProcessor->GetMetricsSize(key));
638 }
639 statsdStats.dumpStats(out);
640 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800641 return NO_ERROR;
642}
643
Yao Chend10f7b12017-12-18 12:53:50 -0800644status_t StatsService::cmd_print_uid_map(FILE* out, const Vector<String8>& args) {
645 if (args.size() > 1) {
646 string pkg;
647 pkg.assign(args[1].c_str(), args[1].size());
648 auto uids = mUidMap->getAppUid(pkg);
649 fprintf(out, "%s -> [ ", pkg.c_str());
650 for (const auto& uid : uids) {
651 fprintf(out, "%d ", uid);
652 }
653 fprintf(out, "]\n");
654 } else {
655 mUidMap->printUidMap(out);
656 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700657 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700658}
659
yro947fbce2017-11-15 22:50:23 -0800660status_t StatsService::cmd_write_data_to_disk(FILE* out) {
661 fprintf(out, "Writing data to disk\n");
Yangster-mac892f3d32018-05-02 14:16:48 -0700662 mProcessor->WriteDataToDisk(ADB_DUMP);
yro947fbce2017-11-15 22:50:23 -0800663 return NO_ERROR;
664}
665
David Chen0b5c90c2018-01-25 16:51:49 -0800666status_t StatsService::cmd_log_app_breadcrumb(FILE* out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800667 bool good = false;
668 int32_t uid;
669 int32_t label;
670 int32_t state;
671 const int argCount = args.size();
672 if (argCount == 3) {
673 // Automatically pick the UID
674 uid = IPCThreadState::self()->getCallingUid();
675 label = atoi(args[1].c_str());
676 state = atoi(args[2].c_str());
677 good = true;
678 } else if (argCount == 4) {
679 uid = atoi(args[1].c_str());
680 // If it's a userdebug or eng build, then the shell user can impersonate other uids.
681 // Otherwise, the uid must match the actual caller's uid.
682 if (mEngBuild || (uid >= 0 && (uid_t)uid == IPCThreadState::self()->getCallingUid())) {
683 label = atoi(args[2].c_str());
684 state = atoi(args[3].c_str());
685 good = true;
686 } else {
687 fprintf(out,
David Chenb639d142018-02-14 17:29:54 -0800688 "Selecting a UID for writing AppBreadcrumb can only be done for other UIDs "
689 "on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800690 }
691 }
692 if (good) {
David Chen0b5c90c2018-01-25 16:51:49 -0800693 fprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
694 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800695 } else {
696 print_cmd_help(out);
697 return UNKNOWN_ERROR;
698 }
699 return NO_ERROR;
700}
701
David Chen1481fe12017-10-16 13:16:34 -0700702status_t StatsService::cmd_print_pulled_metrics(FILE* out, const Vector<String8>& args) {
703 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700704 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700705 if (mStatsPullerManager.Pull(s, getElapsedRealtimeNs(), &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700706 for (const auto& it : stats) {
707 fprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
708 }
709 fprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
710 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700711 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700712 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700713}
714
yro74fed972017-11-27 14:42:42 -0800715status_t StatsService::cmd_remove_all_configs(FILE* out) {
716 fprintf(out, "Removing all configs...\n");
717 VLOG("StatsService::cmd_remove_all_configs was called");
718 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800719 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800720 return NO_ERROR;
721}
722
Yao Chen8d9989b2017-11-18 18:54:50 -0800723status_t StatsService::cmd_dump_memory_info(FILE* out) {
Yao Chen20e9e622018-02-28 11:18:51 -0800724 fprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800725 return NO_ERROR;
726}
727
Chenjie Yue72252b2018-02-01 13:19:35 -0800728status_t StatsService::cmd_clear_puller_cache(FILE* out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800729 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800730 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
731 ipc->getCallingPid(), ipc->getCallingUid());
Chenjie Yufa22d652018-02-05 14:37:48 -0800732 if (checkCallingPermission(String16(kPermissionDump))) {
733 int cleared = mStatsPullerManager.ForceClearPullerCache();
734 fprintf(out, "Puller removed %d cached data!\n", cleared);
735 return NO_ERROR;
736 } else {
737 return PERMISSION_DENIED;
738 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800739}
740
Dianne Hackborn3accca02013-09-20 09:32:11 -0700741Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int64_t>& version,
David Chende701692017-10-05 13:16:02 -0700742 const vector<String16>& app) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600743 ENFORCE_UID(AID_SYSTEM);
744
yro74fed972017-11-27 14:42:42 -0800745 VLOG("StatsService::informAllUidData was called");
David Chenbd125272018-04-04 19:02:50 -0700746 mUidMap->updateMap(getElapsedRealtimeNs(), uid, version, app);
yro74fed972017-11-27 14:42:42 -0800747 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700748
749 return Status::ok();
750}
751
Dianne Hackborn3accca02013-09-20 09:32:11 -0700752Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600753 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700754
Jeff Sharkey6b649252018-04-16 09:50:22 -0600755 VLOG("StatsService::informOnePackage was called");
David Chenbd125272018-04-04 19:02:50 -0700756 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version);
David Chende701692017-10-05 13:16:02 -0700757 return Status::ok();
758}
759
760Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600761 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700762
Jeff Sharkey6b649252018-04-16 09:50:22 -0600763 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -0700764 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -0800765 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -0700766 return Status::ok();
767}
768
Yao Chenef99c4f2017-09-22 16:26:54 -0700769Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600770 ENFORCE_UID(AID_SYSTEM);
771
yro74fed972017-11-27 14:42:42 -0800772 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700773 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800774 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
775 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
776 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -0800777 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -0800778 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -0800779 } else {
780 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
781 }
Bookatz1b0b1142017-09-08 11:58:42 -0700782 return Status::ok();
783}
784
Yangster-mac932ecec2018-02-01 10:23:52 -0800785Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600786 ENFORCE_UID(AID_SYSTEM);
787
Yangster-mac932ecec2018-02-01 10:23:52 -0800788 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700789 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800790 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
791 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
792 if (alarmSet.size() > 0) {
793 VLOG("Found periodic alarm fired.");
794 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
795 } else {
796 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
797 }
798 return Status::ok();
799}
800
Yao Chenef99c4f2017-09-22 16:26:54 -0700801Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600802 ENFORCE_UID(AID_SYSTEM);
803
yro74fed972017-11-27 14:42:42 -0800804 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700805 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -0800806 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700807 return Status::ok();
808}
809
Yao Chenef99c4f2017-09-22 16:26:54 -0700810Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600811 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700812
813 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800814 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -0700815 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700816 return Status::ok();
817}
818
Yangster-mac892f3d32018-05-02 14:16:48 -0700819Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600820 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -0700821 VLOG("StatsService::informDeviceShutdown");
Yangster-mac892f3d32018-05-02 14:16:48 -0700822 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN);
yro947fbce2017-11-15 22:50:23 -0800823 return Status::ok();
824}
825
Yao Chenef99c4f2017-09-22 16:26:54 -0700826void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -0700827 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
828 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -0800829 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -0700830 statsCompanion->statsdReady();
831 } else {
yro74fed972017-11-27 14:42:42 -0800832 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -0700833 }
834}
835
Yao Chenef99c4f2017-09-22 16:26:54 -0700836Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600837 ENFORCE_UID(AID_SYSTEM);
838
yro74fed972017-11-27 14:42:42 -0800839 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -0700840 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
841 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700842 return Status::fromExceptionCode(
843 Status::EX_NULL_POINTER,
844 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700845 }
yro74fed972017-11-27 14:42:42 -0800846 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -0700847 IInterface::asBinder(statsCompanion)->linkToDeath(this);
848 mStatsPullerManager.SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -0800849 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
850 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -0800851 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -0700852 return Status::ok();
853}
854
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700855void StatsService::Startup() {
856 mConfigManager->Startup();
Bookatz906a35c2017-09-20 15:26:44 -0700857}
858
Yao Chen163d2602018-04-10 10:39:53 -0700859void StatsService::OnLogEvent(LogEvent* event, bool reconnectionStarts) {
860 mProcessor->OnLogEvent(event, reconnectionStarts);
Bookatz906a35c2017-09-20 15:26:44 -0700861}
862
Jeff Sharkey6b649252018-04-16 09:50:22 -0600863Status StatsService::getData(int64_t key, const String16& packageName, vector<uint8_t>* output) {
864 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
865
David Chenadaf8b32017-11-03 15:42:08 -0700866 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -0800867 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -0700868 ConfigKey configKey(ipc->getCallingUid(), key);
Yangster-mac9def8e32018-04-17 13:55:51 -0700869 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
870 false /* include_current_bucket*/, true /* include strings */,
871 GET_DATA_CALLED, output);
Bookatz4f716292018-04-10 17:15:12 -0700872 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700873}
874
Jeff Sharkey6b649252018-04-16 09:50:22 -0600875Status StatsService::getMetadata(const String16& packageName, vector<uint8_t>* output) {
876 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
877
David Chen2e8f3802017-11-22 10:56:48 -0800878 IPCThreadState* ipc = IPCThreadState::self();
879 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
880 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -0700881 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
882 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -0800883}
884
Jeff Sharkey6b649252018-04-16 09:50:22 -0600885Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
886 const String16& packageName) {
887 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
888
David Chenadaf8b32017-11-03 15:42:08 -0700889 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -0700890 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -0800891 return Status::ok();
892 } else {
Bookatz4f716292018-04-10 17:15:12 -0700893 ALOGE("Could not parse malformatted StatsdConfig");
894 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
895 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -0800896 }
897}
898
David Chen9fdd4032018-03-20 14:38:56 -0700899bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
900 ConfigKey configKey(uid, key);
901 StatsdConfig cfg;
902 if (config.size() > 0) { // If the config is empty, skip parsing.
903 if (!cfg.ParseFromArray(&config[0], config.size())) {
904 return false;
905 }
906 }
907 mConfigManager->UpdateConfig(configKey, cfg);
908 return true;
909}
910
Jeff Sharkey6b649252018-04-16 09:50:22 -0600911Status StatsService::removeDataFetchOperation(int64_t key, const String16& packageName) {
912 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
913
Bookatz4f716292018-04-10 17:15:12 -0700914 IPCThreadState* ipc = IPCThreadState::self();
915 ConfigKey configKey(ipc->getCallingUid(), key);
916 mConfigManager->RemoveConfigReceiver(configKey);
917 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -0800918}
919
Jeff Sharkey6b649252018-04-16 09:50:22 -0600920Status StatsService::setDataFetchOperation(int64_t key,
921 const sp<android::IBinder>& intentSender,
922 const String16& packageName) {
923 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
924
Bookatz4f716292018-04-10 17:15:12 -0700925 IPCThreadState* ipc = IPCThreadState::self();
926 ConfigKey configKey(ipc->getCallingUid(), key);
927 mConfigManager->SetConfigReceiver(configKey, intentSender);
928 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700929}
930
Jeff Sharkey6b649252018-04-16 09:50:22 -0600931Status StatsService::removeConfiguration(int64_t key, const String16& packageName) {
932 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
933
Bookatz4f716292018-04-10 17:15:12 -0700934 IPCThreadState* ipc = IPCThreadState::self();
935 ConfigKey configKey(ipc->getCallingUid(), key);
936 mConfigManager->RemoveConfig(configKey);
937 SubscriberReporter::getInstance().removeConfig(configKey);
938 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700939}
940
Bookatzc6977972018-01-16 16:55:05 -0800941Status StatsService::setBroadcastSubscriber(int64_t configId,
942 int64_t subscriberId,
Jeff Sharkey6b649252018-04-16 09:50:22 -0600943 const sp<android::IBinder>& intentSender,
944 const String16& packageName) {
945 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
946
Bookatzc6977972018-01-16 16:55:05 -0800947 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -0700948 IPCThreadState* ipc = IPCThreadState::self();
949 ConfigKey configKey(ipc->getCallingUid(), configId);
950 SubscriberReporter::getInstance()
951 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
952 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -0800953}
954
955Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -0600956 int64_t subscriberId,
957 const String16& packageName) {
958 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
959
Bookatzc6977972018-01-16 16:55:05 -0800960 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -0700961 IPCThreadState* ipc = IPCThreadState::self();
962 ConfigKey configKey(ipc->getCallingUid(), configId);
963 SubscriberReporter::getInstance()
964 .unsetBroadcastSubscriber(configKey, subscriberId);
965 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -0800966}
967
David Chen1d7b0cd2017-11-15 14:20:04 -0800968void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -0700969 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -0700970 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
971 if (mProcessor != nullptr) {
972 ALOGW("Reset statsd upon system server restars.");
973 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED);
974 mProcessor->resetConfigs();
975 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -0700976 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
977 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
978 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
979 mStatsPullerManager.SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -0700980}
981
Yao Chenef99c4f2017-09-22 16:26:54 -0700982} // namespace statsd
983} // namespace os
984} // namespace android