blob: e823f6884b29ed8da533fd8fd937a56adebf98d1 [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 }
Yao Chen876889c2018-05-02 11:16:16 -0700337
338 if (!args[0].compare(String8("print-logs"))) {
339 return cmd_print_logs(out, args);
340 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700341 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700342
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700343 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700344 return NO_ERROR;
345}
346
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700347void StatsService::print_cmd_help(FILE* out) {
348 fprintf(out,
349 "usage: adb shell cmd stats print-stats-log [tag_required] "
350 "[timestamp_nsec_optional]\n");
351 fprintf(out, "\n");
352 fprintf(out, "\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800353 fprintf(out, "usage: adb shell cmd stats meminfo\n");
354 fprintf(out, "\n");
355 fprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
356 fprintf(out, " # adb shell stop\n");
357 fprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
358 fprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
359 fprintf(out, " # adb shell start\n");
360 fprintf(out, "\n");
361 fprintf(out, "\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800362 fprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700363 fprintf(out, "\n");
364 fprintf(out, " Prints the UID, app name, version mapping.\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800365 fprintf(out, " PKG Optional package name to print the uids of the package\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700366 fprintf(out, "\n");
367 fprintf(out, "\n");
yro3fca5ba2017-11-17 13:22:52 -0800368 fprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
David Chen1481fe12017-10-16 13:16:34 -0700369 fprintf(out, "\n");
370 fprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
371 fprintf(out, "\n");
372 fprintf(out, "\n");
yro947fbce2017-11-15 22:50:23 -0800373 fprintf(out, "usage: adb shell cmd stats write-to-disk \n");
374 fprintf(out, "\n");
375 fprintf(out, " Flushes all data on memory to disk.\n");
376 fprintf(out, "\n");
377 fprintf(out, "\n");
David Chen0b5c90c2018-01-25 16:51:49 -0800378 fprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
379 fprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800380 fprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
381 fprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
382 fprintf(out, " uid is used.\n");
383 fprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
384 fprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
385 fprintf(out, "\n");
386 fprintf(out, "\n");
yro74fed972017-11-27 14:42:42 -0800387 fprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700388 fprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
389 fprintf(out, "\n");
390 fprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
yro74fed972017-11-27 14:42:42 -0800391 fprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
392 fprintf(out, " provided, then all configs will be removed from memory and disk.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700393 fprintf(out, "\n");
394 fprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
yro74fed972017-11-27 14:42:42 -0800395 fprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700396 fprintf(out, " uid is used.\n");
397 fprintf(out, " NAME The per-uid name to use\n");
Yao Chen5154a372017-10-30 22:57:06 -0700398 fprintf(out, "\n");
yro74fed972017-11-27 14:42:42 -0800399 fprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
400 fprintf(out, "\n be removed from memory and disk!\n");
Yao Chen5154a372017-10-30 22:57:06 -0700401 fprintf(out, "\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800402 fprintf(out, "usage: adb shell cmd stats dump-report [UID] NAME [--proto]\n");
Yao Chen5154a372017-10-30 22:57:06 -0700403 fprintf(out, " Dump all metric data for a configuration.\n");
404 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
405 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
406 fprintf(out, " calling uid is used.\n");
407 fprintf(out, " NAME The name of the configuration\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800408 fprintf(out, " --proto Print proto binary.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700409 fprintf(out, "\n");
410 fprintf(out, "\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800411 fprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
412 fprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
413 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
414 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
415 fprintf(out, " calling uid is used.\n");
416 fprintf(out, " NAME The name of the configuration\n");
417 fprintf(out, "\n");
418 fprintf(out, "\n");
Yao Chenf5acabe2018-01-17 14:10:34 -0800419 fprintf(out, "usage: adb shell cmd stats print-stats\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800420 fprintf(out, " Prints some basic stats.\n");
Tej Singh41b3f9a2018-04-03 17:06:35 -0700421 fprintf(out, " --proto Print proto binary instead of string format.\n");
Chenjie Yufa22d652018-02-05 14:37:48 -0800422 fprintf(out, "\n");
423 fprintf(out, "\n");
424 fprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
425 fprintf(out, " Clear cached puller data.\n");
Yao Chen876889c2018-05-02 11:16:16 -0700426 fprintf(out, "\n");
427 fprintf(out, "usage: adb shell cmd stats print-logs\n");
428 fprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700429}
430
David Chen1d7b0cd2017-11-15 14:20:04 -0800431status_t StatsService::cmd_trigger_broadcast(FILE* out, Vector<String8>& args) {
432 string name;
433 bool good = false;
434 int uid;
435 const int argCount = args.size();
436 if (argCount == 2) {
437 // Automatically pick the UID
438 uid = IPCThreadState::self()->getCallingUid();
439 // TODO: What if this isn't a binder call? Should we fail?
440 name.assign(args[1].c_str(), args[1].size());
441 good = true;
442 } else if (argCount == 3) {
443 // If it's a userdebug or eng build, then the shell user can
444 // impersonate other uids.
445 if (mEngBuild) {
446 const char* s = args[1].c_str();
447 if (*s != '\0') {
448 char* end = NULL;
449 uid = strtol(s, &end, 0);
450 if (*end == '\0') {
451 name.assign(args[2].c_str(), args[2].size());
452 good = true;
453 }
454 }
455 } else {
456 fprintf(out,
457 "The metrics can only be dumped for other UIDs on eng or userdebug "
458 "builds.\n");
459 }
460 }
461 if (!good) {
462 print_cmd_help(out);
463 return UNKNOWN_ERROR;
464 }
David Chend37bc232018-04-12 18:05:11 -0700465 ConfigKey key(uid, StrToInt64(name));
466 auto receiver = mConfigManager->GetConfigReceiver(key);
yro4d889e62017-11-17 15:44:48 -0800467 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen661f7912018-01-22 17:46:24 -0800468 if (sc == nullptr) {
469 VLOG("Could not access statsCompanion");
470 } else if (receiver == nullptr) {
471 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str())
472 } else {
David Chend37bc232018-04-12 18:05:11 -0700473 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
yro74fed972017-11-27 14:42:42 -0800474 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
475 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800476 }
477
David Chenadaf8b32017-11-03 15:42:08 -0700478 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700479}
480
481status_t StatsService::cmd_config(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
482 const int argCount = args.size();
483 if (argCount >= 2) {
484 if (args[1] == "update" || args[1] == "remove") {
485 bool good = false;
486 int uid = -1;
487 string name;
488
489 if (argCount == 3) {
490 // Automatically pick the UID
491 uid = IPCThreadState::self()->getCallingUid();
492 // TODO: What if this isn't a binder call? Should we fail?
493 name.assign(args[2].c_str(), args[2].size());
494 good = true;
495 } else if (argCount == 4) {
496 // If it's a userdebug or eng build, then the shell user can
497 // impersonate other uids.
498 if (mEngBuild) {
499 const char* s = args[2].c_str();
500 if (*s != '\0') {
501 char* end = NULL;
502 uid = strtol(s, &end, 0);
503 if (*end == '\0') {
504 name.assign(args[3].c_str(), args[3].size());
505 good = true;
506 }
507 }
508 } else {
Yao Chen729093d2017-10-16 10:33:26 -0700509 fprintf(err,
510 "The config can only be set for other UIDs on eng or userdebug "
511 "builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700512 }
yroe5f82922018-01-22 18:37:27 -0800513 } else if (argCount == 2 && args[1] == "remove") {
514 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700515 }
516
517 if (!good) {
518 // If arg parsing failed, print the help text and return an error.
519 print_cmd_help(out);
520 return UNKNOWN_ERROR;
521 }
522
523 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800524 char* endp;
525 int64_t configID = strtoll(name.c_str(), &endp, 10);
526 if (endp == name.c_str() || *endp != '\0') {
527 fprintf(err, "Error parsing config ID.\n");
528 return UNKNOWN_ERROR;
529 }
530
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700531 // Read stream into buffer.
532 string buffer;
533 if (!android::base::ReadFdToString(fileno(in), &buffer)) {
534 fprintf(err, "Error reading stream for StatsConfig.\n");
535 return UNKNOWN_ERROR;
536 }
537
538 // Parse buffer.
539 StatsdConfig config;
540 if (!config.ParseFromString(buffer)) {
541 fprintf(err, "Error parsing proto stream for StatsConfig.\n");
542 return UNKNOWN_ERROR;
543 }
544
545 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800546 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700547 } else {
yro74fed972017-11-27 14:42:42 -0800548 if (argCount == 2) {
549 cmd_remove_all_configs(out);
550 } else {
551 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800552 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800553 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700554 }
555
556 return NO_ERROR;
557 }
David Chen0656b7a2017-09-13 15:53:39 -0700558 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700559 print_cmd_help(out);
560 return UNKNOWN_ERROR;
561}
562
Yao Chen729093d2017-10-16 10:33:26 -0700563status_t StatsService::cmd_dump_report(FILE* out, FILE* err, const Vector<String8>& args) {
564 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800565 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700566 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800567 bool proto = false;
Yao Chen729093d2017-10-16 10:33:26 -0700568 int uid;
569 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800570 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
571 proto = true;
572 argCount -= 1;
573 }
Yao Chen729093d2017-10-16 10:33:26 -0700574 if (argCount == 2) {
575 // Automatically pick the UID
576 uid = IPCThreadState::self()->getCallingUid();
577 // TODO: What if this isn't a binder call? Should we fail?
Yao Chen5154a372017-10-30 22:57:06 -0700578 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700579 good = true;
580 } else if (argCount == 3) {
581 // If it's a userdebug or eng build, then the shell user can
582 // impersonate other uids.
583 if (mEngBuild) {
584 const char* s = args[1].c_str();
585 if (*s != '\0') {
586 char* end = NULL;
587 uid = strtol(s, &end, 0);
588 if (*end == '\0') {
589 name.assign(args[2].c_str(), args[2].size());
590 good = true;
591 }
592 }
593 } else {
594 fprintf(out,
595 "The metrics can only be dumped for other UIDs on eng or userdebug "
596 "builds.\n");
597 }
598 }
599 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800600 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800601 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Yangster-mac9def8e32018-04-17 13:55:51 -0700602 false /* include_current_bucket*/,
603 true /* include strings */, ADB_DUMP, &data);
Yao Chen729093d2017-10-16 10:33:26 -0700604 // TODO: print the returned StatsLogReport to file instead of printing to logcat.
Chenjie Yub236c862017-11-28 22:20:44 -0800605 if (proto) {
606 for (size_t i = 0; i < data.size(); i ++) {
607 fprintf(out, "%c", data[i]);
608 }
609 } else {
610 fprintf(out, "Dump report for Config [%d,%s]\n", uid, name.c_str());
611 fprintf(out, "See the StatsLogReport in logcat...\n");
612 }
Yao Chen729093d2017-10-16 10:33:26 -0700613 return android::OK;
614 } else {
615 // If arg parsing failed, print the help text and return an error.
616 print_cmd_help(out);
617 return UNKNOWN_ERROR;
618 }
619 } else {
620 fprintf(out, "Log processor does not exist...\n");
621 return UNKNOWN_ERROR;
622 }
623}
624
Yao Chenb3561512017-11-21 18:07:17 -0800625status_t StatsService::cmd_print_stats(FILE* out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700626 int argCount = args.size();
627 bool proto = false;
628 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
629 proto = true;
630 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800631 }
Yao Chenb3561512017-11-21 18:07:17 -0800632 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700633 if (proto) {
634 vector<uint8_t> data;
635 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
636 for (size_t i = 0; i < data.size(); i ++) {
637 fprintf(out, "%c", data[i]);
638 }
639
640 } else {
641 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
642 for (const ConfigKey& key : configs) {
643 fprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
644 mProcessor->GetMetricsSize(key));
645 }
646 statsdStats.dumpStats(out);
647 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800648 return NO_ERROR;
649}
650
Yao Chend10f7b12017-12-18 12:53:50 -0800651status_t StatsService::cmd_print_uid_map(FILE* out, const Vector<String8>& args) {
652 if (args.size() > 1) {
653 string pkg;
654 pkg.assign(args[1].c_str(), args[1].size());
655 auto uids = mUidMap->getAppUid(pkg);
656 fprintf(out, "%s -> [ ", pkg.c_str());
657 for (const auto& uid : uids) {
658 fprintf(out, "%d ", uid);
659 }
660 fprintf(out, "]\n");
661 } else {
662 mUidMap->printUidMap(out);
663 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700664 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700665}
666
yro947fbce2017-11-15 22:50:23 -0800667status_t StatsService::cmd_write_data_to_disk(FILE* out) {
668 fprintf(out, "Writing data to disk\n");
Yangster-mac892f3d32018-05-02 14:16:48 -0700669 mProcessor->WriteDataToDisk(ADB_DUMP);
yro947fbce2017-11-15 22:50:23 -0800670 return NO_ERROR;
671}
672
David Chen0b5c90c2018-01-25 16:51:49 -0800673status_t StatsService::cmd_log_app_breadcrumb(FILE* out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800674 bool good = false;
675 int32_t uid;
676 int32_t label;
677 int32_t state;
678 const int argCount = args.size();
679 if (argCount == 3) {
680 // Automatically pick the UID
681 uid = IPCThreadState::self()->getCallingUid();
682 label = atoi(args[1].c_str());
683 state = atoi(args[2].c_str());
684 good = true;
685 } else if (argCount == 4) {
686 uid = atoi(args[1].c_str());
687 // If it's a userdebug or eng build, then the shell user can impersonate other uids.
688 // Otherwise, the uid must match the actual caller's uid.
689 if (mEngBuild || (uid >= 0 && (uid_t)uid == IPCThreadState::self()->getCallingUid())) {
690 label = atoi(args[2].c_str());
691 state = atoi(args[3].c_str());
692 good = true;
693 } else {
694 fprintf(out,
David Chenb639d142018-02-14 17:29:54 -0800695 "Selecting a UID for writing AppBreadcrumb can only be done for other UIDs "
696 "on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800697 }
698 }
699 if (good) {
David Chen0b5c90c2018-01-25 16:51:49 -0800700 fprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
701 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800702 } else {
703 print_cmd_help(out);
704 return UNKNOWN_ERROR;
705 }
706 return NO_ERROR;
707}
708
David Chen1481fe12017-10-16 13:16:34 -0700709status_t StatsService::cmd_print_pulled_metrics(FILE* out, const Vector<String8>& args) {
710 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700711 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700712 if (mStatsPullerManager.Pull(s, getElapsedRealtimeNs(), &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700713 for (const auto& it : stats) {
714 fprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
715 }
716 fprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
717 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700718 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700719 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700720}
721
yro74fed972017-11-27 14:42:42 -0800722status_t StatsService::cmd_remove_all_configs(FILE* out) {
723 fprintf(out, "Removing all configs...\n");
724 VLOG("StatsService::cmd_remove_all_configs was called");
725 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800726 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800727 return NO_ERROR;
728}
729
Yao Chen8d9989b2017-11-18 18:54:50 -0800730status_t StatsService::cmd_dump_memory_info(FILE* out) {
Yao Chen20e9e622018-02-28 11:18:51 -0800731 fprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800732 return NO_ERROR;
733}
734
Chenjie Yue72252b2018-02-01 13:19:35 -0800735status_t StatsService::cmd_clear_puller_cache(FILE* out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800736 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800737 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
738 ipc->getCallingPid(), ipc->getCallingUid());
Chenjie Yufa22d652018-02-05 14:37:48 -0800739 if (checkCallingPermission(String16(kPermissionDump))) {
740 int cleared = mStatsPullerManager.ForceClearPullerCache();
741 fprintf(out, "Puller removed %d cached data!\n", cleared);
742 return NO_ERROR;
743 } else {
744 return PERMISSION_DENIED;
745 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800746}
747
Yao Chen876889c2018-05-02 11:16:16 -0700748status_t StatsService::cmd_print_logs(FILE* out, const Vector<String8>& args) {
749 IPCThreadState* ipc = IPCThreadState::self();
750 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", ipc->getCallingPid(),
751 ipc->getCallingUid());
752 if (checkCallingPermission(String16(kPermissionDump))) {
753 bool enabled = true;
754 if (args.size() >= 2) {
755 enabled = atoi(args[1].c_str()) != 0;
756 }
757 mProcessor->setPrintLogs(enabled);
758 return NO_ERROR;
759 } else {
760 return PERMISSION_DENIED;
761 }
762}
763
Dianne Hackborn3accca02013-09-20 09:32:11 -0700764Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int64_t>& version,
David Chende701692017-10-05 13:16:02 -0700765 const vector<String16>& app) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600766 ENFORCE_UID(AID_SYSTEM);
767
yro74fed972017-11-27 14:42:42 -0800768 VLOG("StatsService::informAllUidData was called");
David Chenbd125272018-04-04 19:02:50 -0700769 mUidMap->updateMap(getElapsedRealtimeNs(), uid, version, app);
yro74fed972017-11-27 14:42:42 -0800770 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700771
772 return Status::ok();
773}
774
Dianne Hackborn3accca02013-09-20 09:32:11 -0700775Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600776 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700777
Jeff Sharkey6b649252018-04-16 09:50:22 -0600778 VLOG("StatsService::informOnePackage was called");
David Chenbd125272018-04-04 19:02:50 -0700779 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version);
David Chende701692017-10-05 13:16:02 -0700780 return Status::ok();
781}
782
783Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600784 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700785
Jeff Sharkey6b649252018-04-16 09:50:22 -0600786 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -0700787 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -0800788 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -0700789 return Status::ok();
790}
791
Yao Chenef99c4f2017-09-22 16:26:54 -0700792Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600793 ENFORCE_UID(AID_SYSTEM);
794
yro74fed972017-11-27 14:42:42 -0800795 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700796 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800797 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
798 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
799 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -0800800 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -0800801 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -0800802 } else {
803 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
804 }
Bookatz1b0b1142017-09-08 11:58:42 -0700805 return Status::ok();
806}
807
Yangster-mac932ecec2018-02-01 10:23:52 -0800808Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600809 ENFORCE_UID(AID_SYSTEM);
810
Yangster-mac932ecec2018-02-01 10:23:52 -0800811 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700812 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800813 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
814 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
815 if (alarmSet.size() > 0) {
816 VLOG("Found periodic alarm fired.");
817 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
818 } else {
819 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
820 }
821 return Status::ok();
822}
823
Yao Chenef99c4f2017-09-22 16:26:54 -0700824Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600825 ENFORCE_UID(AID_SYSTEM);
826
yro74fed972017-11-27 14:42:42 -0800827 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700828 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -0800829 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700830 return Status::ok();
831}
832
Yao Chenef99c4f2017-09-22 16:26:54 -0700833Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600834 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700835
836 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800837 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -0700838 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700839 return Status::ok();
840}
841
Yangster-mac892f3d32018-05-02 14:16:48 -0700842Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600843 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -0700844 VLOG("StatsService::informDeviceShutdown");
Yangster-mac892f3d32018-05-02 14:16:48 -0700845 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN);
yro947fbce2017-11-15 22:50:23 -0800846 return Status::ok();
847}
848
Yao Chenef99c4f2017-09-22 16:26:54 -0700849void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -0700850 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
851 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -0800852 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -0700853 statsCompanion->statsdReady();
854 } else {
yro74fed972017-11-27 14:42:42 -0800855 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -0700856 }
857}
858
Yao Chenef99c4f2017-09-22 16:26:54 -0700859Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600860 ENFORCE_UID(AID_SYSTEM);
861
yro74fed972017-11-27 14:42:42 -0800862 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -0700863 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
864 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700865 return Status::fromExceptionCode(
866 Status::EX_NULL_POINTER,
867 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700868 }
yro74fed972017-11-27 14:42:42 -0800869 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -0700870 IInterface::asBinder(statsCompanion)->linkToDeath(this);
871 mStatsPullerManager.SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -0800872 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
873 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -0800874 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -0700875 return Status::ok();
876}
877
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700878void StatsService::Startup() {
879 mConfigManager->Startup();
Bookatz906a35c2017-09-20 15:26:44 -0700880}
881
Yao Chen163d2602018-04-10 10:39:53 -0700882void StatsService::OnLogEvent(LogEvent* event, bool reconnectionStarts) {
883 mProcessor->OnLogEvent(event, reconnectionStarts);
Bookatz906a35c2017-09-20 15:26:44 -0700884}
885
Jeff Sharkey6b649252018-04-16 09:50:22 -0600886Status StatsService::getData(int64_t key, const String16& packageName, vector<uint8_t>* output) {
887 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
888
David Chenadaf8b32017-11-03 15:42:08 -0700889 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -0800890 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -0700891 ConfigKey configKey(ipc->getCallingUid(), key);
Yangster-mac9def8e32018-04-17 13:55:51 -0700892 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
893 false /* include_current_bucket*/, true /* include strings */,
894 GET_DATA_CALLED, output);
Bookatz4f716292018-04-10 17:15:12 -0700895 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700896}
897
Jeff Sharkey6b649252018-04-16 09:50:22 -0600898Status StatsService::getMetadata(const String16& packageName, vector<uint8_t>* output) {
899 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
900
David Chen2e8f3802017-11-22 10:56:48 -0800901 IPCThreadState* ipc = IPCThreadState::self();
902 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
903 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -0700904 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
905 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -0800906}
907
Jeff Sharkey6b649252018-04-16 09:50:22 -0600908Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
909 const String16& packageName) {
910 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
911
David Chenadaf8b32017-11-03 15:42:08 -0700912 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -0700913 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -0800914 return Status::ok();
915 } else {
Bookatz4f716292018-04-10 17:15:12 -0700916 ALOGE("Could not parse malformatted StatsdConfig");
917 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
918 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -0800919 }
920}
921
David Chen9fdd4032018-03-20 14:38:56 -0700922bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
923 ConfigKey configKey(uid, key);
924 StatsdConfig cfg;
925 if (config.size() > 0) { // If the config is empty, skip parsing.
926 if (!cfg.ParseFromArray(&config[0], config.size())) {
927 return false;
928 }
929 }
930 mConfigManager->UpdateConfig(configKey, cfg);
931 return true;
932}
933
Jeff Sharkey6b649252018-04-16 09:50:22 -0600934Status StatsService::removeDataFetchOperation(int64_t key, const String16& packageName) {
935 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
936
Bookatz4f716292018-04-10 17:15:12 -0700937 IPCThreadState* ipc = IPCThreadState::self();
938 ConfigKey configKey(ipc->getCallingUid(), key);
939 mConfigManager->RemoveConfigReceiver(configKey);
940 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -0800941}
942
Jeff Sharkey6b649252018-04-16 09:50:22 -0600943Status StatsService::setDataFetchOperation(int64_t key,
944 const sp<android::IBinder>& intentSender,
945 const String16& packageName) {
946 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
947
Bookatz4f716292018-04-10 17:15:12 -0700948 IPCThreadState* ipc = IPCThreadState::self();
949 ConfigKey configKey(ipc->getCallingUid(), key);
950 mConfigManager->SetConfigReceiver(configKey, intentSender);
951 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700952}
953
Jeff Sharkey6b649252018-04-16 09:50:22 -0600954Status StatsService::removeConfiguration(int64_t key, const String16& packageName) {
955 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
956
Bookatz4f716292018-04-10 17:15:12 -0700957 IPCThreadState* ipc = IPCThreadState::self();
958 ConfigKey configKey(ipc->getCallingUid(), key);
959 mConfigManager->RemoveConfig(configKey);
960 SubscriberReporter::getInstance().removeConfig(configKey);
961 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700962}
963
Bookatzc6977972018-01-16 16:55:05 -0800964Status StatsService::setBroadcastSubscriber(int64_t configId,
965 int64_t subscriberId,
Jeff Sharkey6b649252018-04-16 09:50:22 -0600966 const sp<android::IBinder>& intentSender,
967 const String16& packageName) {
968 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
969
Bookatzc6977972018-01-16 16:55:05 -0800970 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -0700971 IPCThreadState* ipc = IPCThreadState::self();
972 ConfigKey configKey(ipc->getCallingUid(), configId);
973 SubscriberReporter::getInstance()
974 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
975 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -0800976}
977
978Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -0600979 int64_t subscriberId,
980 const String16& packageName) {
981 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
982
Bookatzc6977972018-01-16 16:55:05 -0800983 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -0700984 IPCThreadState* ipc = IPCThreadState::self();
985 ConfigKey configKey(ipc->getCallingUid(), configId);
986 SubscriberReporter::getInstance()
987 .unsetBroadcastSubscriber(configKey, subscriberId);
988 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -0800989}
990
David Chen1d7b0cd2017-11-15 14:20:04 -0800991void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -0700992 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -0700993 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
994 if (mProcessor != nullptr) {
995 ALOGW("Reset statsd upon system server restars.");
996 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED);
997 mProcessor->resetConfigs();
998 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -0700999 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1000 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
1001 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
1002 mStatsPullerManager.SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001003}
1004
Yao Chenef99c4f2017-09-22 16:26:54 -07001005} // namespace statsd
1006} // namespace os
1007} // namespace android