blob: e5e5d5fdd36ef8d75f91514029f1df735434815f [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>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070030#include <binder/IPCThreadState.h>
31#include <binder/IServiceManager.h>
yro87d983c2017-11-14 21:31:43 -080032#include <dirent.h>
David Chen0656b7a2017-09-13 15:53:39 -070033#include <frameworks/base/cmds/statsd/src/statsd_config.pb.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070034#include <private/android_filesystem_config.h>
35#include <utils/Looper.h>
Joe Onorato2cbc2cc2017-08-30 17:03:23 -070036#include <utils/String16.h>
Bookatzb223c4e2018-02-01 15:35:04 -080037#include <statslog.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070038#include <stdio.h>
Yao Chen482d2722017-09-12 13:25:43 -070039#include <stdlib.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070040#include <sys/system_properties.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070041#include <unistd.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070042
43using namespace android;
44
Bookatz906a35c2017-09-20 15:26:44 -070045namespace android {
46namespace os {
47namespace statsd {
48
David Chenadaf8b32017-11-03 15:42:08 -070049constexpr const char* kPermissionDump = "android.permission.DUMP";
yro03faf092017-12-12 00:17:50 -080050#define STATS_SERVICE_DIR "/data/misc/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070051
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070052StatsService::StatsService(const sp<Looper>& handlerLooper)
Yangster-mac932ecec2018-02-01 10:23:52 -080053 : mAnomalyAlarmMonitor(new AlarmMonitor(MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
54 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
55 if (sc != nullptr) {
56 sc->setAnomalyAlarm(timeMillis);
57 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
58 }
59 },
60 [](const sp<IStatsCompanionService>& sc) {
61 if (sc != nullptr) {
62 sc->cancelAnomalyAlarm();
63 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
64 }
65 })),
66 mPeriodicAlarmMonitor(new AlarmMonitor(MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
67 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
68 if (sc != nullptr) {
69 sc->setAlarmForSubscriberTriggering(timeMillis);
70 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
71 }
72 },
73 [](const sp<IStatsCompanionService>& sc) {
74 if (sc != nullptr) {
75 sc->cancelAlarmForSubscriberTriggering();
76 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
77 }
78
79 })) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -070080 mUidMap = new UidMap();
Chenjie Yu80f91122018-01-31 20:24:50 -080081 StatsPuller::SetUidMap(mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -070082 mConfigManager = new ConfigManager();
Yangster-mac932ecec2018-02-01 10:23:52 -080083 mProcessor = new StatsLogProcessor(mUidMap, mAnomalyAlarmMonitor, mPeriodicAlarmMonitor,
84 getElapsedRealtimeSec(), [this](const ConfigKey& key) {
85 sp<IStatsCompanionService> sc = getStatsCompanionService();
86 auto receiver = mConfigManager->GetConfigReceiver(key);
87 if (sc == nullptr) {
88 VLOG("Could not find StatsCompanionService");
89 } else if (receiver == nullptr) {
90 VLOG("Statscompanion could not find a broadcast receiver for %s",
91 key.ToString().c_str());
92 } else {
93 sc->sendDataBroadcast(receiver);
David Chen1d7b0cd2017-11-15 14:20:04 -080094 }
Yangster-mac932ecec2018-02-01 10:23:52 -080095 }
Yangster-mac330af582018-02-08 15:24:38 -080096 );
Joe Onorato9fc9edf2017-10-15 20:08:52 -070097
98 mConfigManager->AddListener(mProcessor);
99
100 init_system_properties();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700101}
102
Yao Chenef99c4f2017-09-22 16:26:54 -0700103StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700104}
105
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700106void StatsService::init_system_properties() {
107 mEngBuild = false;
108 const prop_info* buildType = __system_property_find("ro.build.type");
109 if (buildType != NULL) {
110 __system_property_read_callback(buildType, init_build_type_callback, this);
111 }
David Chen0656b7a2017-09-13 15:53:39 -0700112}
113
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700114void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
115 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700116 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700117 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
118 }
119}
120
121/**
122 * Implement our own because the default binder implementation isn't
123 * properly handling SHELL_COMMAND_TRANSACTION.
124 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700125status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
126 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700127 switch (code) {
128 case SHELL_COMMAND_TRANSACTION: {
129 int in = data.readFileDescriptor();
130 int out = data.readFileDescriptor();
131 int err = data.readFileDescriptor();
132 int argc = data.readInt32();
133 Vector<String8> args;
134 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
135 args.add(String8(data.readString16()));
136 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700137 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
138 sp<IResultReceiver> resultReceiver =
139 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700140
141 FILE* fin = fdopen(in, "r");
142 FILE* fout = fdopen(out, "w");
143 FILE* ferr = fdopen(err, "w");
144
145 if (fin == NULL || fout == NULL || ferr == NULL) {
146 resultReceiver->send(NO_MEMORY);
147 } else {
148 err = command(fin, fout, ferr, args);
149 resultReceiver->send(err);
150 }
151
152 if (fin != NULL) {
153 fflush(fin);
154 fclose(fin);
155 }
156 if (fout != NULL) {
157 fflush(fout);
158 fclose(fout);
159 }
160 if (fout != NULL) {
161 fflush(ferr);
162 fclose(ferr);
163 }
164
165 return NO_ERROR;
166 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700167 default: { return BnStatsManager::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700168 }
169}
170
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700171/**
172 * Write debugging data about statsd.
173 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700174status_t StatsService::dump(int fd, const Vector<String16>& args) {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700175 FILE* out = fdopen(fd, "w");
176 if (out == NULL) {
177 return NO_MEMORY; // the fd is already open
178 }
179
Yao Chen884c8c12018-01-26 10:36:25 -0800180 bool verbose = false;
Tej Singh41b3f9a2018-04-03 17:06:35 -0700181 bool proto = false;
Yao Chen884c8c12018-01-26 10:36:25 -0800182 if (args.size() > 0 && !args[0].compare(String16("-v"))) {
183 verbose = true;
184 }
Tej Singh41b3f9a2018-04-03 17:06:35 -0700185 if (args.size() > 0 && !args[args.size()-1].compare(String16("--proto"))) {
186 proto = true;
187 }
Yao Chen884c8c12018-01-26 10:36:25 -0800188
Tej Singh41b3f9a2018-04-03 17:06:35 -0700189 dump_impl(out, verbose, proto);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700190
191 fclose(out);
192 return NO_ERROR;
193}
194
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700195/**
Tej Singh41b3f9a2018-04-03 17:06:35 -0700196 * Write debugging data about statsd in text or proto format.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700197 */
Tej Singh41b3f9a2018-04-03 17:06:35 -0700198void StatsService::dump_impl(FILE* out, bool verbose, bool proto) {
199 if (proto) {
200 vector<uint8_t> data;
201 StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
202 for (size_t i = 0; i < data.size(); i ++) {
203 fprintf(out, "%c", data[i]);
204 }
205 } else {
206 StatsdStats::getInstance().dumpStats(out);
207 mProcessor->dumpStates(out, verbose);
208 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700209}
210
211/**
212 * Implementation of the adb shell cmd stats command.
213 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700214status_t StatsService::command(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700215 // TODO: Permission check
216
217 const int argCount = args.size();
218 if (argCount >= 1) {
219 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700220 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700221 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700222 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700223
David Chende701692017-10-05 13:16:02 -0700224 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800225 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700226 }
Yao Chen729093d2017-10-16 10:33:26 -0700227
228 if (!args[0].compare(String8("dump-report"))) {
229 return cmd_dump_report(out, err, args);
230 }
David Chen1481fe12017-10-16 13:16:34 -0700231
232 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
233 return cmd_print_pulled_metrics(out, args);
234 }
David Chenadaf8b32017-11-03 15:42:08 -0700235
236 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800237 return cmd_trigger_broadcast(out, args);
238 }
239
240 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800241 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700242 }
yro87d983c2017-11-14 21:31:43 -0800243
Yao Chen8d9989b2017-11-18 18:54:50 -0800244 if (!args[0].compare(String8("meminfo"))) {
245 return cmd_dump_memory_info(out);
246 }
yro947fbce2017-11-15 22:50:23 -0800247
248 if (!args[0].compare(String8("write-to-disk"))) {
249 return cmd_write_data_to_disk(out);
250 }
Bookatzb223c4e2018-02-01 15:35:04 -0800251
David Chen0b5c90c2018-01-25 16:51:49 -0800252 if (!args[0].compare(String8("log-app-breadcrumb"))) {
253 return cmd_log_app_breadcrumb(out, args);
Bookatzb223c4e2018-02-01 15:35:04 -0800254 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800255
256 if (!args[0].compare(String8("clear-puller-cache"))) {
257 return cmd_clear_puller_cache(out);
258 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700259 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700260
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700261 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700262 return NO_ERROR;
263}
264
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700265void StatsService::print_cmd_help(FILE* out) {
266 fprintf(out,
267 "usage: adb shell cmd stats print-stats-log [tag_required] "
268 "[timestamp_nsec_optional]\n");
269 fprintf(out, "\n");
270 fprintf(out, "\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800271 fprintf(out, "usage: adb shell cmd stats meminfo\n");
272 fprintf(out, "\n");
273 fprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
274 fprintf(out, " # adb shell stop\n");
275 fprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
276 fprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
277 fprintf(out, " # adb shell start\n");
278 fprintf(out, "\n");
279 fprintf(out, "\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800280 fprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700281 fprintf(out, "\n");
282 fprintf(out, " Prints the UID, app name, version mapping.\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800283 fprintf(out, " PKG Optional package name to print the uids of the package\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700284 fprintf(out, "\n");
285 fprintf(out, "\n");
yro3fca5ba2017-11-17 13:22:52 -0800286 fprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
David Chen1481fe12017-10-16 13:16:34 -0700287 fprintf(out, "\n");
288 fprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
289 fprintf(out, "\n");
290 fprintf(out, "\n");
yro947fbce2017-11-15 22:50:23 -0800291 fprintf(out, "usage: adb shell cmd stats write-to-disk \n");
292 fprintf(out, "\n");
293 fprintf(out, " Flushes all data on memory to disk.\n");
294 fprintf(out, "\n");
295 fprintf(out, "\n");
David Chen0b5c90c2018-01-25 16:51:49 -0800296 fprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
297 fprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800298 fprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
299 fprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
300 fprintf(out, " uid is used.\n");
301 fprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
302 fprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
303 fprintf(out, "\n");
304 fprintf(out, "\n");
yro74fed972017-11-27 14:42:42 -0800305 fprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700306 fprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
307 fprintf(out, "\n");
308 fprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
yro74fed972017-11-27 14:42:42 -0800309 fprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
310 fprintf(out, " provided, then all configs will be removed from memory and disk.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700311 fprintf(out, "\n");
312 fprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
yro74fed972017-11-27 14:42:42 -0800313 fprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700314 fprintf(out, " uid is used.\n");
315 fprintf(out, " NAME The per-uid name to use\n");
Yao Chen5154a372017-10-30 22:57:06 -0700316 fprintf(out, "\n");
yro74fed972017-11-27 14:42:42 -0800317 fprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
318 fprintf(out, "\n be removed from memory and disk!\n");
Yao Chen5154a372017-10-30 22:57:06 -0700319 fprintf(out, "\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800320 fprintf(out, "usage: adb shell cmd stats dump-report [UID] NAME [--proto]\n");
Yao Chen5154a372017-10-30 22:57:06 -0700321 fprintf(out, " Dump all metric data for a configuration.\n");
322 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
323 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
324 fprintf(out, " calling uid is used.\n");
325 fprintf(out, " NAME The name of the configuration\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800326 fprintf(out, " --proto Print proto binary.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700327 fprintf(out, "\n");
328 fprintf(out, "\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800329 fprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
330 fprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
331 fprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
332 fprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
333 fprintf(out, " calling uid is used.\n");
334 fprintf(out, " NAME The name of the configuration\n");
335 fprintf(out, "\n");
336 fprintf(out, "\n");
Yao Chenf5acabe2018-01-17 14:10:34 -0800337 fprintf(out, "usage: adb shell cmd stats print-stats\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800338 fprintf(out, " Prints some basic stats.\n");
Tej Singh41b3f9a2018-04-03 17:06:35 -0700339 fprintf(out, " --proto Print proto binary instead of string format.\n");
Chenjie Yufa22d652018-02-05 14:37:48 -0800340 fprintf(out, "\n");
341 fprintf(out, "\n");
342 fprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
343 fprintf(out, " Clear cached puller data.\n");
David Chenadaf8b32017-11-03 15:42:08 -0700344}
345
David Chen1d7b0cd2017-11-15 14:20:04 -0800346status_t StatsService::cmd_trigger_broadcast(FILE* out, Vector<String8>& args) {
347 string name;
348 bool good = false;
349 int uid;
350 const int argCount = args.size();
351 if (argCount == 2) {
352 // Automatically pick the UID
353 uid = IPCThreadState::self()->getCallingUid();
354 // TODO: What if this isn't a binder call? Should we fail?
355 name.assign(args[1].c_str(), args[1].size());
356 good = true;
357 } else if (argCount == 3) {
358 // If it's a userdebug or eng build, then the shell user can
359 // impersonate other uids.
360 if (mEngBuild) {
361 const char* s = args[1].c_str();
362 if (*s != '\0') {
363 char* end = NULL;
364 uid = strtol(s, &end, 0);
365 if (*end == '\0') {
366 name.assign(args[2].c_str(), args[2].size());
367 good = true;
368 }
369 }
370 } else {
371 fprintf(out,
372 "The metrics can only be dumped for other UIDs on eng or userdebug "
373 "builds.\n");
374 }
375 }
376 if (!good) {
377 print_cmd_help(out);
378 return UNKNOWN_ERROR;
379 }
Yangster-mac94e197c2018-01-02 16:03:03 -0800380 auto receiver = mConfigManager->GetConfigReceiver(ConfigKey(uid, StrToInt64(name)));
yro4d889e62017-11-17 15:44:48 -0800381 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen661f7912018-01-22 17:46:24 -0800382 if (sc == nullptr) {
383 VLOG("Could not access statsCompanion");
384 } else if (receiver == nullptr) {
385 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str())
386 } else {
387 sc->sendDataBroadcast(receiver);
yro74fed972017-11-27 14:42:42 -0800388 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
389 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800390 }
391
David Chenadaf8b32017-11-03 15:42:08 -0700392 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700393}
394
395status_t StatsService::cmd_config(FILE* in, FILE* out, FILE* err, Vector<String8>& args) {
396 const int argCount = args.size();
397 if (argCount >= 2) {
398 if (args[1] == "update" || args[1] == "remove") {
399 bool good = false;
400 int uid = -1;
401 string name;
402
403 if (argCount == 3) {
404 // Automatically pick the UID
405 uid = IPCThreadState::self()->getCallingUid();
406 // TODO: What if this isn't a binder call? Should we fail?
407 name.assign(args[2].c_str(), args[2].size());
408 good = true;
409 } else if (argCount == 4) {
410 // If it's a userdebug or eng build, then the shell user can
411 // impersonate other uids.
412 if (mEngBuild) {
413 const char* s = args[2].c_str();
414 if (*s != '\0') {
415 char* end = NULL;
416 uid = strtol(s, &end, 0);
417 if (*end == '\0') {
418 name.assign(args[3].c_str(), args[3].size());
419 good = true;
420 }
421 }
422 } else {
Yao Chen729093d2017-10-16 10:33:26 -0700423 fprintf(err,
424 "The config can only be set for other UIDs on eng or userdebug "
425 "builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700426 }
yroe5f82922018-01-22 18:37:27 -0800427 } else if (argCount == 2 && args[1] == "remove") {
428 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700429 }
430
431 if (!good) {
432 // If arg parsing failed, print the help text and return an error.
433 print_cmd_help(out);
434 return UNKNOWN_ERROR;
435 }
436
437 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800438 char* endp;
439 int64_t configID = strtoll(name.c_str(), &endp, 10);
440 if (endp == name.c_str() || *endp != '\0') {
441 fprintf(err, "Error parsing config ID.\n");
442 return UNKNOWN_ERROR;
443 }
444
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700445 // Read stream into buffer.
446 string buffer;
447 if (!android::base::ReadFdToString(fileno(in), &buffer)) {
448 fprintf(err, "Error reading stream for StatsConfig.\n");
449 return UNKNOWN_ERROR;
450 }
451
452 // Parse buffer.
453 StatsdConfig config;
454 if (!config.ParseFromString(buffer)) {
455 fprintf(err, "Error parsing proto stream for StatsConfig.\n");
456 return UNKNOWN_ERROR;
457 }
458
459 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800460 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700461 } else {
yro74fed972017-11-27 14:42:42 -0800462 if (argCount == 2) {
463 cmd_remove_all_configs(out);
464 } else {
465 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800466 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800467 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700468 }
469
470 return NO_ERROR;
471 }
David Chen0656b7a2017-09-13 15:53:39 -0700472 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700473 print_cmd_help(out);
474 return UNKNOWN_ERROR;
475}
476
Yao Chen729093d2017-10-16 10:33:26 -0700477status_t StatsService::cmd_dump_report(FILE* out, FILE* err, const Vector<String8>& args) {
478 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800479 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700480 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800481 bool proto = false;
Yao Chen729093d2017-10-16 10:33:26 -0700482 int uid;
483 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800484 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
485 proto = true;
486 argCount -= 1;
487 }
Yao Chen729093d2017-10-16 10:33:26 -0700488 if (argCount == 2) {
489 // Automatically pick the UID
490 uid = IPCThreadState::self()->getCallingUid();
491 // TODO: What if this isn't a binder call? Should we fail?
Yao Chen5154a372017-10-30 22:57:06 -0700492 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700493 good = true;
494 } else if (argCount == 3) {
495 // If it's a userdebug or eng build, then the shell user can
496 // impersonate other uids.
497 if (mEngBuild) {
498 const char* s = args[1].c_str();
499 if (*s != '\0') {
500 char* end = NULL;
501 uid = strtol(s, &end, 0);
502 if (*end == '\0') {
503 name.assign(args[2].c_str(), args[2].size());
504 good = true;
505 }
506 }
507 } else {
508 fprintf(out,
509 "The metrics can only be dumped for other UIDs on eng or userdebug "
510 "builds.\n");
511 }
512 }
513 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800514 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800515 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Yangster-mace68f3a52018-04-04 00:01:43 -0700516 false /* include_current_bucket*/, &data);
Yao Chen729093d2017-10-16 10:33:26 -0700517 // TODO: print the returned StatsLogReport to file instead of printing to logcat.
Chenjie Yub236c862017-11-28 22:20:44 -0800518 if (proto) {
519 for (size_t i = 0; i < data.size(); i ++) {
520 fprintf(out, "%c", data[i]);
521 }
522 } else {
523 fprintf(out, "Dump report for Config [%d,%s]\n", uid, name.c_str());
524 fprintf(out, "See the StatsLogReport in logcat...\n");
525 }
Yao Chen729093d2017-10-16 10:33:26 -0700526 return android::OK;
527 } else {
528 // If arg parsing failed, print the help text and return an error.
529 print_cmd_help(out);
530 return UNKNOWN_ERROR;
531 }
532 } else {
533 fprintf(out, "Log processor does not exist...\n");
534 return UNKNOWN_ERROR;
535 }
536}
537
Yao Chenb3561512017-11-21 18:07:17 -0800538status_t StatsService::cmd_print_stats(FILE* out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700539 int argCount = args.size();
540 bool proto = false;
541 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
542 proto = true;
543 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800544 }
Yao Chenb3561512017-11-21 18:07:17 -0800545 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700546 if (proto) {
547 vector<uint8_t> data;
548 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
549 for (size_t i = 0; i < data.size(); i ++) {
550 fprintf(out, "%c", data[i]);
551 }
552
553 } else {
554 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
555 for (const ConfigKey& key : configs) {
556 fprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
557 mProcessor->GetMetricsSize(key));
558 }
559 statsdStats.dumpStats(out);
560 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800561 return NO_ERROR;
562}
563
Yao Chend10f7b12017-12-18 12:53:50 -0800564status_t StatsService::cmd_print_uid_map(FILE* out, const Vector<String8>& args) {
565 if (args.size() > 1) {
566 string pkg;
567 pkg.assign(args[1].c_str(), args[1].size());
568 auto uids = mUidMap->getAppUid(pkg);
569 fprintf(out, "%s -> [ ", pkg.c_str());
570 for (const auto& uid : uids) {
571 fprintf(out, "%d ", uid);
572 }
573 fprintf(out, "]\n");
574 } else {
575 mUidMap->printUidMap(out);
576 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700577 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700578}
579
yro947fbce2017-11-15 22:50:23 -0800580status_t StatsService::cmd_write_data_to_disk(FILE* out) {
581 fprintf(out, "Writing data to disk\n");
582 mProcessor->WriteDataToDisk();
583 return NO_ERROR;
584}
585
David Chen0b5c90c2018-01-25 16:51:49 -0800586status_t StatsService::cmd_log_app_breadcrumb(FILE* out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800587 bool good = false;
588 int32_t uid;
589 int32_t label;
590 int32_t state;
591 const int argCount = args.size();
592 if (argCount == 3) {
593 // Automatically pick the UID
594 uid = IPCThreadState::self()->getCallingUid();
595 label = atoi(args[1].c_str());
596 state = atoi(args[2].c_str());
597 good = true;
598 } else if (argCount == 4) {
599 uid = atoi(args[1].c_str());
600 // If it's a userdebug or eng build, then the shell user can impersonate other uids.
601 // Otherwise, the uid must match the actual caller's uid.
602 if (mEngBuild || (uid >= 0 && (uid_t)uid == IPCThreadState::self()->getCallingUid())) {
603 label = atoi(args[2].c_str());
604 state = atoi(args[3].c_str());
605 good = true;
606 } else {
607 fprintf(out,
David Chenb639d142018-02-14 17:29:54 -0800608 "Selecting a UID for writing AppBreadcrumb can only be done for other UIDs "
609 "on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800610 }
611 }
612 if (good) {
David Chen0b5c90c2018-01-25 16:51:49 -0800613 fprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
614 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800615 } else {
616 print_cmd_help(out);
617 return UNKNOWN_ERROR;
618 }
619 return NO_ERROR;
620}
621
David Chen1481fe12017-10-16 13:16:34 -0700622status_t StatsService::cmd_print_pulled_metrics(FILE* out, const Vector<String8>& args) {
623 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700624 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu1a0a9412018-03-28 10:07:22 -0700625 if (mStatsPullerManager.Pull(s, getElapsedRealtimeNs(), &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700626 for (const auto& it : stats) {
627 fprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
628 }
629 fprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
630 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700631 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700632 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700633}
634
yro74fed972017-11-27 14:42:42 -0800635status_t StatsService::cmd_remove_all_configs(FILE* out) {
636 fprintf(out, "Removing all configs...\n");
637 VLOG("StatsService::cmd_remove_all_configs was called");
638 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800639 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800640 return NO_ERROR;
641}
642
Yao Chen8d9989b2017-11-18 18:54:50 -0800643status_t StatsService::cmd_dump_memory_info(FILE* out) {
Yao Chen20e9e622018-02-28 11:18:51 -0800644 fprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800645 return NO_ERROR;
646}
647
Chenjie Yue72252b2018-02-01 13:19:35 -0800648status_t StatsService::cmd_clear_puller_cache(FILE* out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800649 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800650 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
651 ipc->getCallingPid(), ipc->getCallingUid());
Chenjie Yufa22d652018-02-05 14:37:48 -0800652 if (checkCallingPermission(String16(kPermissionDump))) {
653 int cleared = mStatsPullerManager.ForceClearPullerCache();
654 fprintf(out, "Puller removed %d cached data!\n", cleared);
655 return NO_ERROR;
656 } else {
657 return PERMISSION_DENIED;
658 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800659}
660
Dianne Hackborn3accca02013-09-20 09:32:11 -0700661Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int64_t>& version,
David Chende701692017-10-05 13:16:02 -0700662 const vector<String16>& app) {
yro74fed972017-11-27 14:42:42 -0800663 VLOG("StatsService::informAllUidData was called");
David Chende701692017-10-05 13:16:02 -0700664
665 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
666 return Status::fromExceptionCode(Status::EX_SECURITY,
667 "Only system uid can call informAllUidData");
668 }
669
David Chenbd125272018-04-04 19:02:50 -0700670 mUidMap->updateMap(getElapsedRealtimeNs(), uid, version, app);
yro74fed972017-11-27 14:42:42 -0800671 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700672
673 return Status::ok();
674}
675
Dianne Hackborn3accca02013-09-20 09:32:11 -0700676Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version) {
yro74fed972017-11-27 14:42:42 -0800677 VLOG("StatsService::informOnePackage was called");
David Chende701692017-10-05 13:16:02 -0700678
679 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
680 return Status::fromExceptionCode(Status::EX_SECURITY,
681 "Only system uid can call informOnePackage");
682 }
David Chenbd125272018-04-04 19:02:50 -0700683 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version);
David Chende701692017-10-05 13:16:02 -0700684 return Status::ok();
685}
686
687Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
yro74fed972017-11-27 14:42:42 -0800688 VLOG("StatsService::informOnePackageRemoved was called");
David Chende701692017-10-05 13:16:02 -0700689
690 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
691 return Status::fromExceptionCode(Status::EX_SECURITY,
692 "Only system uid can call informOnePackageRemoved");
693 }
David Chenbd125272018-04-04 19:02:50 -0700694 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -0800695 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -0700696 return Status::ok();
697}
698
Yao Chenef99c4f2017-09-22 16:26:54 -0700699Status StatsService::informAnomalyAlarmFired() {
yro74fed972017-11-27 14:42:42 -0800700 VLOG("StatsService::informAnomalyAlarmFired was called");
Bookatz1b0b1142017-09-08 11:58:42 -0700701
702 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
703 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700704 "Only system uid can call informAnomalyAlarmFired");
Bookatz1b0b1142017-09-08 11:58:42 -0700705 }
Yangster-mac932ecec2018-02-01 10:23:52 -0800706
Yangster-macb142cc82018-03-30 15:22:08 -0700707 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800708 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
709 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
710 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -0800711 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -0800712 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -0800713 } else {
714 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
715 }
Bookatz1b0b1142017-09-08 11:58:42 -0700716 return Status::ok();
717}
718
Yangster-mac932ecec2018-02-01 10:23:52 -0800719Status StatsService::informAlarmForSubscriberTriggeringFired() {
720 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
721
722 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
723 return Status::fromExceptionCode(
724 Status::EX_SECURITY,
725 "Only system uid can call informAlarmForSubscriberTriggeringFired");
726 }
727
Yangster-macb142cc82018-03-30 15:22:08 -0700728 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800729 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
730 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
731 if (alarmSet.size() > 0) {
732 VLOG("Found periodic alarm fired.");
733 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
734 } else {
735 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
736 }
737 return Status::ok();
738}
739
Yao Chenef99c4f2017-09-22 16:26:54 -0700740Status StatsService::informPollAlarmFired() {
yro74fed972017-11-27 14:42:42 -0800741 VLOG("StatsService::informPollAlarmFired was called");
Bookatz1b0b1142017-09-08 11:58:42 -0700742
743 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
744 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700745 "Only system uid can call informPollAlarmFired");
Bookatz1b0b1142017-09-08 11:58:42 -0700746 }
747
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700748 mStatsPullerManager.OnAlarmFired();
Chenjie Yub3dda412017-10-24 13:41:59 -0700749
yro74fed972017-11-27 14:42:42 -0800750 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700751
752 return Status::ok();
753}
754
Yao Chenef99c4f2017-09-22 16:26:54 -0700755Status StatsService::systemRunning() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700756 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
757 return Status::fromExceptionCode(Status::EX_SECURITY,
Yao Chenef99c4f2017-09-22 16:26:54 -0700758 "Only system uid can call systemRunning");
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700759 }
760
761 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800762 VLOG("StatsService::systemRunning");
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700763
Bookatzb487b552017-09-18 11:26:01 -0700764 sayHiToStatsCompanion();
765
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700766 return Status::ok();
767}
768
yro947fbce2017-11-15 22:50:23 -0800769Status StatsService::writeDataToDisk() {
770 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
771 return Status::fromExceptionCode(Status::EX_SECURITY,
772 "Only system uid can call systemRunning");
773 }
774
yro74fed972017-11-27 14:42:42 -0800775 VLOG("StatsService::writeDataToDisk");
yro947fbce2017-11-15 22:50:23 -0800776
777 mProcessor->WriteDataToDisk();
778
779 return Status::ok();
780}
781
Yao Chenef99c4f2017-09-22 16:26:54 -0700782void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -0700783 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
784 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -0800785 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -0700786 statsCompanion->statsdReady();
787 } else {
yro74fed972017-11-27 14:42:42 -0800788 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -0700789 }
790}
791
Yao Chenef99c4f2017-09-22 16:26:54 -0700792Status StatsService::statsCompanionReady() {
yro74fed972017-11-27 14:42:42 -0800793 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -0700794
795 if (IPCThreadState::self()->getCallingUid() != AID_SYSTEM) {
796 return Status::fromExceptionCode(Status::EX_SECURITY,
797 "Only system uid can call statsCompanionReady");
798 }
799
800 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
801 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700802 return Status::fromExceptionCode(
803 Status::EX_NULL_POINTER,
804 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700805 }
yro74fed972017-11-27 14:42:42 -0800806 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -0700807 IInterface::asBinder(statsCompanion)->linkToDeath(this);
808 mStatsPullerManager.SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -0800809 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
810 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -0800811 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -0700812 return Status::ok();
813}
814
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700815void StatsService::Startup() {
816 mConfigManager->Startup();
Bookatz906a35c2017-09-20 15:26:44 -0700817}
818
Yangster-macd40053e2018-01-09 16:29:22 -0800819void StatsService::OnLogEvent(LogEvent* event) {
Joe Onoratoc4dfae52017-10-17 23:38:21 -0700820 mProcessor->OnLogEvent(event);
Bookatz906a35c2017-09-20 15:26:44 -0700821}
822
Yangster-mac94e197c2018-01-02 16:03:03 -0800823Status StatsService::getData(int64_t key, vector<uint8_t>* output) {
David Chenadaf8b32017-11-03 15:42:08 -0700824 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -0800825 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -0700826 if (!checkCallingPermission(String16(kPermissionDump))) {
David Chenadaf8b32017-11-03 15:42:08 -0700827 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
828 }
Bookatz4f716292018-04-10 17:15:12 -0700829 ConfigKey configKey(ipc->getCallingUid(), key);
830 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
831 false /* include_current_bucket*/, output);
832 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700833}
834
David Chen2e8f3802017-11-22 10:56:48 -0800835Status StatsService::getMetadata(vector<uint8_t>* output) {
836 IPCThreadState* ipc = IPCThreadState::self();
837 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
838 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -0700839 if (!checkCallingPermission(String16(kPermissionDump))) {
David Chen2e8f3802017-11-22 10:56:48 -0800840 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
841 }
Bookatz4f716292018-04-10 17:15:12 -0700842 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
843 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -0800844}
845
Bookatz4f716292018-04-10 17:15:12 -0700846Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config) {
847 if (!checkCallingPermission(String16(kPermissionDump))) {
848 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
849 }
David Chenadaf8b32017-11-03 15:42:08 -0700850 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -0700851 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -0800852 return Status::ok();
853 } else {
Bookatz4f716292018-04-10 17:15:12 -0700854 ALOGE("Could not parse malformatted StatsdConfig");
855 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
856 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -0800857 }
858}
859
David Chen9fdd4032018-03-20 14:38:56 -0700860bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
861 ConfigKey configKey(uid, key);
862 StatsdConfig cfg;
863 if (config.size() > 0) { // If the config is empty, skip parsing.
864 if (!cfg.ParseFromArray(&config[0], config.size())) {
865 return false;
866 }
867 }
868 mConfigManager->UpdateConfig(configKey, cfg);
869 return true;
870}
871
Bookatz4f716292018-04-10 17:15:12 -0700872Status StatsService::removeDataFetchOperation(int64_t key) {
873 if (!checkCallingPermission(String16(kPermissionDump))) {
David Chen661f7912018-01-22 17:46:24 -0800874 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
875 }
Bookatz4f716292018-04-10 17:15:12 -0700876 IPCThreadState* ipc = IPCThreadState::self();
877 ConfigKey configKey(ipc->getCallingUid(), key);
878 mConfigManager->RemoveConfigReceiver(configKey);
879 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -0800880}
881
Bookatz4f716292018-04-10 17:15:12 -0700882Status StatsService::setDataFetchOperation(int64_t key, const sp<android::IBinder>& intentSender) {
883 if (!checkCallingPermission(String16(kPermissionDump))) {
David Chenadaf8b32017-11-03 15:42:08 -0700884 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
yro31eb67b2017-10-24 13:33:21 -0700885 }
Bookatz4f716292018-04-10 17:15:12 -0700886 IPCThreadState* ipc = IPCThreadState::self();
887 ConfigKey configKey(ipc->getCallingUid(), key);
888 mConfigManager->SetConfigReceiver(configKey, intentSender);
889 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700890}
891
Bookatz4f716292018-04-10 17:15:12 -0700892Status StatsService::removeConfiguration(int64_t key) {
893 if (!checkCallingPermission(String16(kPermissionDump))) {
David Chenadaf8b32017-11-03 15:42:08 -0700894 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
yro31eb67b2017-10-24 13:33:21 -0700895 }
Bookatz4f716292018-04-10 17:15:12 -0700896 IPCThreadState* ipc = IPCThreadState::self();
897 ConfigKey configKey(ipc->getCallingUid(), key);
898 mConfigManager->RemoveConfig(configKey);
899 SubscriberReporter::getInstance().removeConfig(configKey);
900 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -0700901}
902
Bookatzc6977972018-01-16 16:55:05 -0800903Status StatsService::setBroadcastSubscriber(int64_t configId,
904 int64_t subscriberId,
Bookatz4f716292018-04-10 17:15:12 -0700905 const sp<android::IBinder>& intentSender) {
Bookatzc6977972018-01-16 16:55:05 -0800906 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -0700907 if (!checkCallingPermission(String16(kPermissionDump))) {
Bookatzc6977972018-01-16 16:55:05 -0800908 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
909 }
Bookatz4f716292018-04-10 17:15:12 -0700910 IPCThreadState* ipc = IPCThreadState::self();
911 ConfigKey configKey(ipc->getCallingUid(), configId);
912 SubscriberReporter::getInstance()
913 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
914 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -0800915}
916
917Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Bookatz4f716292018-04-10 17:15:12 -0700918 int64_t subscriberId) {
Bookatzc6977972018-01-16 16:55:05 -0800919 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -0700920 if (!checkCallingPermission(String16(kPermissionDump))) {
Bookatzc6977972018-01-16 16:55:05 -0800921 return Status::fromExceptionCode(binder::Status::EX_SECURITY);
922 }
Bookatz4f716292018-04-10 17:15:12 -0700923 IPCThreadState* ipc = IPCThreadState::self();
924 ConfigKey configKey(ipc->getCallingUid(), configId);
925 SubscriberReporter::getInstance()
926 .unsetBroadcastSubscriber(configKey, subscriberId);
927 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -0800928}
929
930
David Chen1d7b0cd2017-11-15 14:20:04 -0800931void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -0700932 ALOGW("statscompanion service died");
933 mProcessor->WriteDataToDisk();
934 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
935 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
936 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
937 mStatsPullerManager.SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -0700938}
939
Yao Chenef99c4f2017-09-22 16:26:54 -0700940} // namespace statsd
941} // namespace os
942} // namespace android