blob: 168833fc8c8baf37a7e80c806eee325f9da50537 [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>
Tej Singh53f9dee2019-04-30 17:45:54 -070030#include <android-base/strings.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070031#include <binder/IPCThreadState.h>
Jeff Sharkey6b649252018-04-16 09:50:22 -060032#include <binder/PermissionController.h>
Chenjie Yu6b1667c2019-01-18 10:09:33 -080033#include <cutils/multiuser.h>
David Chen0656b7a2017-09-13 15:53:39 -070034#include <frameworks/base/cmds/statsd/src/statsd_config.pb.h>
Max Dashouk11e0d402019-05-16 16:58:07 -070035#include <frameworks/base/cmds/statsd/src/uid_data.pb.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070036#include <private/android_filesystem_config.h>
Bookatzb223c4e2018-02-01 15:35:04 -080037#include <statslog.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070038#include <stdio.h>
Yao Chen482d2722017-09-12 13:25:43 -070039#include <stdlib.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070040#include <sys/system_properties.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070041#include <unistd.h>
Yao Chena80e5c02018-09-04 13:55:29 -070042#include <utils/String16.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070043
44using namespace android;
45
Jeff Sharkey6b649252018-04-16 09:50:22 -060046using android::base::StringPrintf;
Bookatzff71cad2018-09-20 17:17:49 -070047using android::util::FIELD_COUNT_REPEATED;
48using android::util::FIELD_TYPE_MESSAGE;
Jeff Sharkey6b649252018-04-16 09:50:22 -060049
Bookatz906a35c2017-09-20 15:26:44 -070050namespace android {
51namespace os {
52namespace statsd {
53
David Chenadaf8b32017-11-03 15:42:08 -070054constexpr const char* kPermissionDump = "android.permission.DUMP";
Jeff Sharkey6b649252018-04-16 09:50:22 -060055constexpr const char* kPermissionUsage = "android.permission.PACKAGE_USAGE_STATS";
56
57constexpr const char* kOpUsage = "android:get_usage_stats";
58
yro03faf092017-12-12 00:17:50 -080059#define STATS_SERVICE_DIR "/data/misc/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070060
Bookatzff71cad2018-09-20 17:17:49 -070061// for StatsDataDumpProto
62const int FIELD_ID_REPORTS_LIST = 1;
63
Jeff Sharkey6b649252018-04-16 09:50:22 -060064static binder::Status ok() {
65 return binder::Status::ok();
66}
67
68static binder::Status exception(uint32_t code, const std::string& msg) {
69 ALOGE("%s (%d)", msg.c_str(), code);
70 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
71}
72
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -080073static bool checkPermission(const char* permission) {
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -080074 pid_t pid = IPCThreadState::self()->getCallingPid();
75 uid_t uid = IPCThreadState::self()->getCallingUid();
Jonathan Nguyena0e6de12020-01-28 18:33:55 -080076 return checkPermissionForIds(permission, pid, uid);
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -080077}
78
Jeff Sharkey6b649252018-04-16 09:50:22 -060079binder::Status checkUid(uid_t expectedUid) {
80 uid_t uid = IPCThreadState::self()->getCallingUid();
81 if (uid == expectedUid || uid == AID_ROOT) {
82 return ok();
83 } else {
84 return exception(binder::Status::EX_SECURITY,
85 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
86 }
87}
88
89binder::Status checkDumpAndUsageStats(const String16& packageName) {
90 pid_t pid = IPCThreadState::self()->getCallingPid();
91 uid_t uid = IPCThreadState::self()->getCallingUid();
92
93 // Root, system, and shell always have access
94 if (uid == AID_ROOT || uid == AID_SYSTEM || uid == AID_SHELL) {
95 return ok();
96 }
97
98 // Caller must be granted these permissions
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -080099 if (!checkPermission(kPermissionDump)) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600100 return exception(binder::Status::EX_SECURITY,
101 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionDump));
102 }
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -0800103 if (!checkPermission(kPermissionUsage)) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600104 return exception(binder::Status::EX_SECURITY,
105 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionUsage));
106 }
107
108 // Caller must also have usage stats op granted
109 PermissionController pc;
110 switch (pc.noteOp(String16(kOpUsage), uid, packageName)) {
111 case PermissionController::MODE_ALLOWED:
112 case PermissionController::MODE_DEFAULT:
113 return ok();
114 default:
115 return exception(binder::Status::EX_SECURITY,
116 StringPrintf("UID %d / PID %d lacks app-op %s", uid, pid, kOpUsage));
117 }
118}
119
120#define ENFORCE_UID(uid) { \
121 binder::Status status = checkUid((uid)); \
122 if (!status.isOk()) { \
123 return status; \
124 } \
125}
126
127#define ENFORCE_DUMP_AND_USAGE_STATS(packageName) { \
128 binder::Status status = checkDumpAndUsageStats(packageName); \
129 if (!status.isOk()) { \
130 return status; \
131 } \
132}
133
Yao Chen0f861862019-03-27 11:51:15 -0700134StatsService::StatsService(const sp<Looper>& handlerLooper, shared_ptr<LogEventQueue> queue)
135 : mAnomalyAlarmMonitor(new AlarmMonitor(
136 MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
137 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
138 if (sc != nullptr) {
139 sc->setAnomalyAlarm(timeMillis);
140 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
141 }
142 },
143 [](const sp<IStatsCompanionService>& sc) {
144 if (sc != nullptr) {
145 sc->cancelAnomalyAlarm();
146 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
147 }
148 })),
149 mPeriodicAlarmMonitor(new AlarmMonitor(
150 MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
151 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
152 if (sc != nullptr) {
153 sc->setAlarmForSubscriberTriggering(timeMillis);
154 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
155 }
156 },
157 [](const sp<IStatsCompanionService>& sc) {
158 if (sc != nullptr) {
159 sc->cancelAlarmForSubscriberTriggering();
160 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
161 }
162 })),
163 mEventQueue(queue) {
Yao Chen4ce07292019-02-13 13:06:36 -0800164 mUidMap = UidMap::getInstance();
Chenjie Yue2219202018-06-08 10:07:51 -0700165 mPullerManager = new StatsPullerManager();
Chenjie Yu80f91122018-01-31 20:24:50 -0800166 StatsPuller::SetUidMap(mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700167 mConfigManager = new ConfigManager();
Chenjie Yue2219202018-06-08 10:07:51 -0700168 mProcessor = new StatsLogProcessor(
169 mUidMap, mPullerManager, mAnomalyAlarmMonitor, mPeriodicAlarmMonitor,
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800170 getElapsedRealtimeNs(),
171 [this](const ConfigKey& key) {
Jeffrey Huangad213742019-12-16 13:50:06 -0800172 sp<IPendingIntentRef> receiver = mConfigManager->GetConfigReceiver(key);
173 if (receiver == nullptr) {
174 VLOG("Could not find a broadcast receiver for %s",
175 key.ToString().c_str());
Chenjie Yue2219202018-06-08 10:07:51 -0700176 return false;
Jeffrey Huangad213742019-12-16 13:50:06 -0800177 } else if (receiver->sendDataBroadcast(
178 mProcessor->getLastReportTimeNs(key)).isOk()) {
Chenjie Yue2219202018-06-08 10:07:51 -0700179 return true;
Jeffrey Huangad213742019-12-16 13:50:06 -0800180 } else {
181 VLOG("Failed to send a broadcast for receiver %s",
182 key.ToString().c_str());
183 return false;
Chenjie Yue2219202018-06-08 10:07:51 -0700184 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800185 },
186 [this](const int& uid, const vector<int64_t>& activeConfigs) {
Jeffrey Huang47537a12020-01-06 15:35:34 -0800187 sp<IPendingIntentRef> receiver =
188 mConfigManager->GetActiveConfigsChangedReceiver(uid);
189 if (receiver == nullptr) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800190 VLOG("Could not find receiver for uid %d", uid);
191 return false;
Jeffrey Huang47537a12020-01-06 15:35:34 -0800192 } else if (receiver->sendActiveConfigsChangedBroadcast(activeConfigs).isOk()) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800193 VLOG("StatsService::active configs broadcast succeeded for uid %d" , uid);
194 return true;
Jeffrey Huang47537a12020-01-06 15:35:34 -0800195 } else {
196 VLOG("StatsService::active configs broadcast failed for uid %d" , uid);
197 return false;
Tej Singh6ede28b2019-01-29 17:06:54 -0800198 }
Chenjie Yue2219202018-06-08 10:07:51 -0700199 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700200
Tej Singh9ec159a2019-11-14 11:59:48 -0800201 mUidMap->setListener(mProcessor);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700202 mConfigManager->AddListener(mProcessor);
203
204 init_system_properties();
Yao Chen0f861862019-03-27 11:51:15 -0700205
206 if (mEventQueue != nullptr) {
207 std::thread pushedEventThread([this] { readLogs(); });
208 pushedEventThread.detach();
209 }
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700210}
211
Yao Chenef99c4f2017-09-22 16:26:54 -0700212StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700213}
214
Yao Chen0f861862019-03-27 11:51:15 -0700215/* Runs on a dedicated thread to process pushed events. */
216void StatsService::readLogs() {
217 // Read forever..... long live statsd
218 while (1) {
219 // Block until an event is available.
220 auto event = mEventQueue->waitPop();
221 // Pass it to StatsLogProcess to all configs/metrics
222 // At this point, the LogEventQueue is not blocked, so that the socketListener
223 // can read events from the socket and write to buffer to avoid data drop.
224 mProcessor->OnLogEvent(event.get());
225 // The ShellSubscriber is only used by shell for local debugging.
226 if (mShellSubscriber != nullptr) {
227 mShellSubscriber->onLogEvent(*event);
228 }
229 }
230}
231
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700232void StatsService::init_system_properties() {
233 mEngBuild = false;
234 const prop_info* buildType = __system_property_find("ro.build.type");
235 if (buildType != NULL) {
236 __system_property_read_callback(buildType, init_build_type_callback, this);
237 }
David Chen0656b7a2017-09-13 15:53:39 -0700238}
239
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700240void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
241 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700242 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700243 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
244 }
245}
246
247/**
248 * Implement our own because the default binder implementation isn't
249 * properly handling SHELL_COMMAND_TRANSACTION.
250 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700251status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
252 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700253 switch (code) {
254 case SHELL_COMMAND_TRANSACTION: {
255 int in = data.readFileDescriptor();
256 int out = data.readFileDescriptor();
257 int err = data.readFileDescriptor();
258 int argc = data.readInt32();
259 Vector<String8> args;
260 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
261 args.add(String8(data.readString16()));
262 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700263 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
264 sp<IResultReceiver> resultReceiver =
265 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700266
Yao Chena80e5c02018-09-04 13:55:29 -0700267 err = command(in, out, err, args, resultReceiver);
Tej Singhc9250ce2019-09-20 19:28:53 -0700268 if (resultReceiver != nullptr) {
269 resultReceiver->send(err);
270 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700271 return NO_ERROR;
272 }
Jeffrey Huang161c0752019-12-11 14:47:32 -0800273 default: { return BnStatsd::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700274 }
275}
276
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700277/**
Bookatzff71cad2018-09-20 17:17:49 -0700278 * Write data from statsd.
279 * Format for statsdStats: adb shell dumpsys stats --metadata [-v] [--proto]
280 * Format for data report: adb shell dumpsys stats [anything other than --metadata] [--proto]
281 * Anything ending in --proto will be in proto format.
282 * Anything without --metadata as the first argument will be report information.
283 * (bugreports call "adb shell dumpsys stats --dump-priority NORMAL -a --proto")
284 * TODO: Come up with a more robust method of enacting <serviceutils/PriorityDumper.h>.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700285 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700286status_t StatsService::dump(int fd, const Vector<String16>& args) {
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -0800287 if (!checkPermission(kPermissionDump)) {
Tej Singhdd83d702018-04-10 17:24:50 -0700288 return PERMISSION_DENIED;
289 }
Bookatzff71cad2018-09-20 17:17:49 -0700290 int lastArg = args.size() - 1;
291 bool asProto = false;
292 if (lastArg >= 0 && !args[lastArg].compare(String16("--proto"))) { // last argument
293 asProto = true;
294 lastArg--;
Yao Chen884c8c12018-01-26 10:36:25 -0800295 }
Bookatzff71cad2018-09-20 17:17:49 -0700296 if (args.size() > 0 && !args[0].compare(String16("--metadata"))) { // first argument
297 // Request is to dump statsd stats.
298 bool verbose = false;
299 if (lastArg >= 0 && !args[lastArg].compare(String16("-v"))) {
300 verbose = true;
301 lastArg--;
302 }
303 dumpStatsdStats(fd, verbose, asProto);
304 } else {
305 // Request is to dump statsd report data.
306 if (asProto) {
307 dumpIncidentSection(fd);
308 } else {
309 dprintf(fd, "Non-proto format of stats data dump not available; see proto version.\n");
310 }
Tej Singh41b3f9a2018-04-03 17:06:35 -0700311 }
Yao Chen884c8c12018-01-26 10:36:25 -0800312
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700313 return NO_ERROR;
314}
315
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700316/**
Tej Singh41b3f9a2018-04-03 17:06:35 -0700317 * Write debugging data about statsd in text or proto format.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700318 */
Bookatzff71cad2018-09-20 17:17:49 -0700319void StatsService::dumpStatsdStats(int out, bool verbose, bool proto) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700320 if (proto) {
321 vector<uint8_t> data;
322 StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
323 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700324 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700325 }
326 } else {
327 StatsdStats::getInstance().dumpStats(out);
328 mProcessor->dumpStates(out, verbose);
329 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700330}
331
332/**
Bookatzff71cad2018-09-20 17:17:49 -0700333 * Write stats report data in StatsDataDumpProto incident section format.
334 */
335void StatsService::dumpIncidentSection(int out) {
336 ProtoOutputStream proto;
337 for (const ConfigKey& configKey : mConfigManager->GetAllConfigKeys()) {
338 uint64_t reportsListToken =
339 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS_LIST);
340 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
341 true /* includeCurrentBucket */, false /* erase_data */,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000342 ADB_DUMP,
343 FAST,
344 &proto);
Bookatzff71cad2018-09-20 17:17:49 -0700345 proto.end(reportsListToken);
346 proto.flush(out);
Bookatzc71d9012018-12-19 12:28:38 -0800347 proto.clear();
Bookatzff71cad2018-09-20 17:17:49 -0700348 }
349}
350
351/**
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700352 * Implementation of the adb shell cmd stats command.
353 */
Yao Chena80e5c02018-09-04 13:55:29 -0700354status_t StatsService::command(int in, int out, int err, Vector<String8>& args,
355 sp<IResultReceiver> resultReceiver) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600356 uid_t uid = IPCThreadState::self()->getCallingUid();
357 if (uid != AID_ROOT && uid != AID_SHELL) {
358 return PERMISSION_DENIED;
359 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700360
361 const int argCount = args.size();
362 if (argCount >= 1) {
363 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700364 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700365 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700366 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700367
David Chende701692017-10-05 13:16:02 -0700368 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800369 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700370 }
Yao Chen729093d2017-10-16 10:33:26 -0700371
372 if (!args[0].compare(String8("dump-report"))) {
Bookatzff71cad2018-09-20 17:17:49 -0700373 return cmd_dump_report(out, args);
Yao Chen729093d2017-10-16 10:33:26 -0700374 }
David Chen1481fe12017-10-16 13:16:34 -0700375
376 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
377 return cmd_print_pulled_metrics(out, args);
378 }
David Chenadaf8b32017-11-03 15:42:08 -0700379
380 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800381 return cmd_trigger_broadcast(out, args);
382 }
383
384 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800385 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700386 }
yro87d983c2017-11-14 21:31:43 -0800387
Yao Chen8d9989b2017-11-18 18:54:50 -0800388 if (!args[0].compare(String8("meminfo"))) {
389 return cmd_dump_memory_info(out);
390 }
yro947fbce2017-11-15 22:50:23 -0800391
392 if (!args[0].compare(String8("write-to-disk"))) {
393 return cmd_write_data_to_disk(out);
394 }
Bookatzb223c4e2018-02-01 15:35:04 -0800395
David Chen0b5c90c2018-01-25 16:51:49 -0800396 if (!args[0].compare(String8("log-app-breadcrumb"))) {
397 return cmd_log_app_breadcrumb(out, args);
Bookatzb223c4e2018-02-01 15:35:04 -0800398 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800399
Tej Singh53f9dee2019-04-30 17:45:54 -0700400 if (!args[0].compare(String8("log-binary-push"))) {
401 return cmd_log_binary_push(out, args);
402 }
403
Chenjie Yufa22d652018-02-05 14:37:48 -0800404 if (!args[0].compare(String8("clear-puller-cache"))) {
405 return cmd_clear_puller_cache(out);
406 }
Yao Chen876889c2018-05-02 11:16:16 -0700407
408 if (!args[0].compare(String8("print-logs"))) {
409 return cmd_print_logs(out, args);
410 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800411 if (!args[0].compare(String8("send-active-configs"))) {
412 return cmd_trigger_active_config_broadcast(out, args);
413 }
Yao Chena80e5c02018-09-04 13:55:29 -0700414 if (!args[0].compare(String8("data-subscribe"))) {
Tej Singhc9250ce2019-09-20 19:28:53 -0700415 {
416 std::lock_guard<std::mutex> lock(mShellSubscriberMutex);
417 if (mShellSubscriber == nullptr) {
418 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
419 }
Yao Chena80e5c02018-09-04 13:55:29 -0700420 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800421 int timeoutSec = -1;
422 if (argCount >= 2) {
423 timeoutSec = atoi(args[1].c_str());
424 }
Tej Singhc9250ce2019-09-20 19:28:53 -0700425 if (resultReceiver == nullptr) {
426 ALOGI("Null resultReceiver given, no subscription will be started");
427 return UNEXPECTED_NULL;
428 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800429 mShellSubscriber->startNewSubscription(in, out, resultReceiver, timeoutSec);
Yao Chena80e5c02018-09-04 13:55:29 -0700430 return NO_ERROR;
431 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700432 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700433
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700434 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700435 return NO_ERROR;
436}
437
Yao Chena80e5c02018-09-04 13:55:29 -0700438void StatsService::print_cmd_help(int out) {
439 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700440 "usage: adb shell cmd stats print-stats-log [tag_required] "
441 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700442 dprintf(out, "\n");
443 dprintf(out, "\n");
444 dprintf(out, "usage: adb shell cmd stats meminfo\n");
445 dprintf(out, "\n");
446 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
447 dprintf(out, " # adb shell stop\n");
448 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
449 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
450 dprintf(out, " # adb shell start\n");
451 dprintf(out, "\n");
452 dprintf(out, "\n");
453 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
454 dprintf(out, "\n");
455 dprintf(out, " Prints the UID, app name, version mapping.\n");
456 dprintf(out, " PKG Optional package name to print the uids of the package\n");
457 dprintf(out, "\n");
458 dprintf(out, "\n");
459 dprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
460 dprintf(out, "\n");
461 dprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
462 dprintf(out, "\n");
463 dprintf(out, "\n");
464 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
465 dprintf(out, "\n");
466 dprintf(out, " Flushes all data on memory to disk.\n");
467 dprintf(out, "\n");
468 dprintf(out, "\n");
469 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
470 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
471 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
472 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
473 dprintf(out, " uid is used.\n");
474 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
475 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
476 dprintf(out, "\n");
477 dprintf(out, "\n");
Tej Singh53f9dee2019-04-30 17:45:54 -0700478 dprintf(out,
479 "usage: adb shell cmd stats log-binary-push NAME VERSION STAGING ROLLBACK_ENABLED "
480 "LOW_LATENCY STATE EXPERIMENT_IDS\n");
481 dprintf(out, " Log a binary push state changed event.\n");
482 dprintf(out, " NAME The train name.\n");
483 dprintf(out, " VERSION The train version code.\n");
484 dprintf(out, " STAGING If this train requires a restart.\n");
485 dprintf(out, " ROLLBACK_ENABLED If rollback should be enabled for this install.\n");
486 dprintf(out, " LOW_LATENCY If the train requires low latency monitoring.\n");
487 dprintf(out, " STATE The status of the train push.\n");
488 dprintf(out, " Integer value of the enum in atoms.proto.\n");
489 dprintf(out, " EXPERIMENT_IDS Comma separated list of experiment ids.\n");
490 dprintf(out, " Leave blank for none.\n");
491 dprintf(out, "\n");
492 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700493 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
494 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
495 dprintf(out, "\n");
496 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
497 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
498 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
499 dprintf(out, "\n");
500 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
501 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
502 dprintf(out, " uid is used.\n");
503 dprintf(out, " NAME The per-uid name to use\n");
504 dprintf(out, "\n");
505 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
506 dprintf(out, "\n be removed from memory and disk!\n");
507 dprintf(out, "\n");
508 dprintf(out,
Bookatz3e906582018-12-10 17:26:58 -0800509 "usage: adb shell cmd stats dump-report [UID] NAME [--keep_data] "
510 "[--include_current_bucket] [--proto]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700511 dprintf(out, " Dump all metric data for a configuration.\n");
512 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
513 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
514 dprintf(out, " calling uid is used.\n");
515 dprintf(out, " NAME The name of the configuration\n");
Bookatz3e906582018-12-10 17:26:58 -0800516 dprintf(out, " --keep_data Do NOT erase the data upon dumping it.\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700517 dprintf(out, " --proto Print proto binary.\n");
518 dprintf(out, "\n");
519 dprintf(out, "\n");
520 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
521 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
522 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
523 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
524 dprintf(out, " calling uid is used.\n");
525 dprintf(out, " NAME The name of the configuration\n");
526 dprintf(out, "\n");
527 dprintf(out, "\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800528 dprintf(out,
529 "usage: adb shell cmd stats send-active-configs [--uid=UID] [--configs] "
530 "[NAME1] [NAME2] [NAME3..]\n");
531 dprintf(out, " Send a broadcast that informs the subscriber of the current active configs.\n");
532 dprintf(out, " --uid=UID The uid of the configurations. It is only possible to pass\n");
533 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
534 dprintf(out, " calling uid is used.\n");
535 dprintf(out, " --configs Send the list of configs in the name list instead of\n");
536 dprintf(out, " the currently active configs\n");
537 dprintf(out, " NAME LIST List of configuration names to be included in the broadcast.\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800538 dprintf(out, "\n");
539 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700540 dprintf(out, "usage: adb shell cmd stats print-stats\n");
541 dprintf(out, " Prints some basic stats.\n");
542 dprintf(out, " --proto Print proto binary instead of string format.\n");
543 dprintf(out, "\n");
544 dprintf(out, "\n");
545 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
546 dprintf(out, " Clear cached puller data.\n");
547 dprintf(out, "\n");
548 dprintf(out, "usage: adb shell cmd stats print-logs\n");
549 dprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700550}
551
Yao Chena80e5c02018-09-04 13:55:29 -0700552status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800553 string name;
554 bool good = false;
555 int uid;
556 const int argCount = args.size();
557 if (argCount == 2) {
558 // Automatically pick the UID
559 uid = IPCThreadState::self()->getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800560 name.assign(args[1].c_str(), args[1].size());
561 good = true;
562 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800563 good = getUidFromArgs(args, 1, uid);
564 if (!good) {
565 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
566 "other UIDs on eng or userdebug builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800567 }
Bookatzd2386572018-12-14 15:53:14 -0800568 name.assign(args[2].c_str(), args[2].size());
David Chen1d7b0cd2017-11-15 14:20:04 -0800569 }
570 if (!good) {
571 print_cmd_help(out);
572 return UNKNOWN_ERROR;
573 }
David Chend37bc232018-04-12 18:05:11 -0700574 ConfigKey key(uid, StrToInt64(name));
Jeffrey Huangad213742019-12-16 13:50:06 -0800575 sp<IPendingIntentRef> receiver = mConfigManager->GetConfigReceiver(key);
576 if (receiver == nullptr) {
577 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str());
578 return UNKNOWN_ERROR;
579 } else if (receiver->sendDataBroadcast(
580 mProcessor->getLastReportTimeNs(key)).isOk()) {
yro74fed972017-11-27 14:42:42 -0800581 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
582 args[2].c_str());
Jeffrey Huangad213742019-12-16 13:50:06 -0800583 } else {
584 VLOG("StatsService::trigger broadcast failed to %s, %s", args[1].c_str(),
585 args[2].c_str());
586 return UNKNOWN_ERROR;
yro4d889e62017-11-17 15:44:48 -0800587 }
David Chenadaf8b32017-11-03 15:42:08 -0700588 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700589}
590
Tej Singh6ede28b2019-01-29 17:06:54 -0800591status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
592 const int argCount = args.size();
593 int uid;
594 vector<int64_t> configIds;
595 if (argCount == 1) {
596 // Automatically pick the uid and send a broadcast that has no active configs.
597 uid = IPCThreadState::self()->getCallingUid();
598 mProcessor->GetActiveConfigs(uid, configIds);
599 } else {
600 int curArg = 1;
601 if(args[curArg].find("--uid=") == 0) {
602 string uidArgStr(args[curArg].c_str());
603 string uidStr = uidArgStr.substr(6);
604 if (!getUidFromString(uidStr.c_str(), uid)) {
605 dprintf(out, "Invalid UID. Note that the config can only be set for "
606 "other UIDs on eng or userdebug builds.\n");
607 return UNKNOWN_ERROR;
608 }
609 curArg++;
610 } else {
611 uid = IPCThreadState::self()->getCallingUid();
612 }
613 if (curArg == argCount || args[curArg] != "--configs") {
614 VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
615 mProcessor->GetActiveConfigs(uid, configIds);
616 } else {
617 // Flag specified, use the given list of configs.
618 curArg++;
619 for (int i = curArg; i < argCount; i++) {
620 char* endp;
621 int64_t configID = strtoll(args[i].c_str(), &endp, 10);
622 if (endp == args[i].c_str() || *endp != '\0') {
623 dprintf(out, "Error parsing config ID.\n");
624 return UNKNOWN_ERROR;
625 }
626 VLOG("Adding config id %ld", static_cast<long>(configID));
627 configIds.push_back(configID);
628 }
629 }
630 }
Jeffrey Huang47537a12020-01-06 15:35:34 -0800631 sp<IPendingIntentRef> receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
632 if (receiver == nullptr) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800633 VLOG("Could not find receiver for uid %d", uid);
Jeffrey Huang47537a12020-01-06 15:35:34 -0800634 return UNKNOWN_ERROR;
635 } else if (receiver->sendActiveConfigsChangedBroadcast(configIds).isOk()) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800636 VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
Jeffrey Huang47537a12020-01-06 15:35:34 -0800637 } else {
638 VLOG("StatsService::trigger active configs changed broadcast failed for uid %d", uid);
639 return UNKNOWN_ERROR;
Tej Singh6ede28b2019-01-29 17:06:54 -0800640 }
641 return NO_ERROR;
642}
643
Yao Chena80e5c02018-09-04 13:55:29 -0700644status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700645 const int argCount = args.size();
646 if (argCount >= 2) {
647 if (args[1] == "update" || args[1] == "remove") {
648 bool good = false;
649 int uid = -1;
650 string name;
651
652 if (argCount == 3) {
653 // Automatically pick the UID
654 uid = IPCThreadState::self()->getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700655 name.assign(args[2].c_str(), args[2].size());
656 good = true;
657 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800658 good = getUidFromArgs(args, 2, uid);
659 if (!good) {
660 dprintf(err, "Invalid UID. Note that the config can only be set for "
661 "other UIDs on eng or userdebug builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700662 }
Bookatzd2386572018-12-14 15:53:14 -0800663 name.assign(args[3].c_str(), args[3].size());
yroe5f82922018-01-22 18:37:27 -0800664 } else if (argCount == 2 && args[1] == "remove") {
665 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700666 }
667
668 if (!good) {
669 // If arg parsing failed, print the help text and return an error.
670 print_cmd_help(out);
671 return UNKNOWN_ERROR;
672 }
673
674 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800675 char* endp;
676 int64_t configID = strtoll(name.c_str(), &endp, 10);
677 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700678 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800679 return UNKNOWN_ERROR;
680 }
681
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700682 // Read stream into buffer.
683 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700684 if (!android::base::ReadFdToString(in, &buffer)) {
685 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700686 return UNKNOWN_ERROR;
687 }
688
689 // Parse buffer.
690 StatsdConfig config;
691 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700692 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700693 return UNKNOWN_ERROR;
694 }
695
696 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800697 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700698 } else {
yro74fed972017-11-27 14:42:42 -0800699 if (argCount == 2) {
700 cmd_remove_all_configs(out);
701 } else {
702 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800703 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800704 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700705 }
706
707 return NO_ERROR;
708 }
David Chen0656b7a2017-09-13 15:53:39 -0700709 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700710 print_cmd_help(out);
711 return UNKNOWN_ERROR;
712}
713
Bookatzff71cad2018-09-20 17:17:49 -0700714status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700715 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800716 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700717 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800718 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700719 bool includeCurrentBucket = false;
Bookatz3e906582018-12-10 17:26:58 -0800720 bool eraseData = true;
Yao Chen729093d2017-10-16 10:33:26 -0700721 int uid;
722 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800723 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
724 proto = true;
725 argCount -= 1;
726 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700727 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
728 includeCurrentBucket = true;
729 argCount -= 1;
730 }
Bookatz3e906582018-12-10 17:26:58 -0800731 if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
732 eraseData = false;
733 argCount -= 1;
734 }
Yao Chen729093d2017-10-16 10:33:26 -0700735 if (argCount == 2) {
736 // Automatically pick the UID
737 uid = IPCThreadState::self()->getCallingUid();
Yao Chen5154a372017-10-30 22:57:06 -0700738 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700739 good = true;
740 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800741 good = getUidFromArgs(args, 1, uid);
742 if (!good) {
743 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
744 "other UIDs on eng or userdebug builds.\n");
Yao Chen729093d2017-10-16 10:33:26 -0700745 }
Bookatzd2386572018-12-14 15:53:14 -0800746 name.assign(args[2].c_str(), args[2].size());
Yao Chen729093d2017-10-16 10:33:26 -0700747 }
748 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800749 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800750 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000751 includeCurrentBucket, eraseData, ADB_DUMP,
752 NO_TIME_CONSTRAINTS,
753 &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800754 if (proto) {
755 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700756 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800757 }
758 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700759 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800760 }
Yao Chen729093d2017-10-16 10:33:26 -0700761 return android::OK;
762 } else {
763 // If arg parsing failed, print the help text and return an error.
764 print_cmd_help(out);
765 return UNKNOWN_ERROR;
766 }
767 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700768 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700769 return UNKNOWN_ERROR;
770 }
771}
772
Yao Chena80e5c02018-09-04 13:55:29 -0700773status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700774 int argCount = args.size();
775 bool proto = false;
776 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
777 proto = true;
778 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800779 }
Yao Chenb3561512017-11-21 18:07:17 -0800780 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700781 if (proto) {
782 vector<uint8_t> data;
783 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
784 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700785 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700786 }
787
788 } else {
789 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
790 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700791 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700792 mProcessor->GetMetricsSize(key));
793 }
794 statsdStats.dumpStats(out);
795 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800796 return NO_ERROR;
797}
798
Yao Chena80e5c02018-09-04 13:55:29 -0700799status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800800 if (args.size() > 1) {
801 string pkg;
802 pkg.assign(args[1].c_str(), args[1].size());
803 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700804 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800805 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700806 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800807 }
Yao Chena80e5c02018-09-04 13:55:29 -0700808 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800809 } else {
810 mUidMap->printUidMap(out);
811 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700812 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700813}
814
Yao Chena80e5c02018-09-04 13:55:29 -0700815status_t StatsService::cmd_write_data_to_disk(int out) {
816 dprintf(out, "Writing data to disk\n");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000817 mProcessor->WriteDataToDisk(ADB_DUMP, NO_TIME_CONSTRAINTS);
yro947fbce2017-11-15 22:50:23 -0800818 return NO_ERROR;
819}
820
Yao Chena80e5c02018-09-04 13:55:29 -0700821status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800822 bool good = false;
823 int32_t uid;
824 int32_t label;
825 int32_t state;
826 const int argCount = args.size();
827 if (argCount == 3) {
828 // Automatically pick the UID
829 uid = IPCThreadState::self()->getCallingUid();
830 label = atoi(args[1].c_str());
831 state = atoi(args[2].c_str());
832 good = true;
833 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800834 good = getUidFromArgs(args, 1, uid);
835 if (!good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700836 dprintf(out,
Bookatzd2386572018-12-14 15:53:14 -0800837 "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
838 "done for other UIDs on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800839 }
Bookatzd2386572018-12-14 15:53:14 -0800840 label = atoi(args[2].c_str());
841 state = atoi(args[3].c_str());
Bookatzb223c4e2018-02-01 15:35:04 -0800842 }
843 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700844 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
David Chen0b5c90c2018-01-25 16:51:49 -0800845 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800846 } else {
847 print_cmd_help(out);
848 return UNKNOWN_ERROR;
849 }
850 return NO_ERROR;
851}
852
Tej Singh53f9dee2019-04-30 17:45:54 -0700853status_t StatsService::cmd_log_binary_push(int out, const Vector<String8>& args) {
854 // Security checks are done in the sendBinaryPushStateChanged atom.
855 const int argCount = args.size();
856 if (argCount != 7 && argCount != 8) {
857 dprintf(out, "Incorrect number of argument supplied\n");
858 return UNKNOWN_ERROR;
859 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800860 string trainName = string(args[1].c_str());
Tej Singh53f9dee2019-04-30 17:45:54 -0700861 int64_t trainVersion = strtoll(args[2].c_str(), nullptr, 10);
Tej Singh53f9dee2019-04-30 17:45:54 -0700862 int32_t state = atoi(args[6].c_str());
863 vector<int64_t> experimentIds;
864 if (argCount == 8) {
865 vector<string> experimentIdsString = android::base::Split(string(args[7].c_str()), ",");
866 for (string experimentIdString : experimentIdsString) {
867 int64_t experimentId = strtoll(experimentIdString.c_str(), nullptr, 10);
868 experimentIds.push_back(experimentId);
869 }
870 }
871 dprintf(out, "Logging BinaryPushStateChanged\n");
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800872 vector<uint8_t> experimentIdBytes;
873 writeExperimentIdsToProto(experimentIds, &experimentIdBytes);
874 LogEvent event(trainName, trainVersion, args[3], args[4], args[5], state, experimentIdBytes, 0);
875 mProcessor->OnLogEvent(&event);
Tej Singh53f9dee2019-04-30 17:45:54 -0700876 return NO_ERROR;
877}
878
Yao Chena80e5c02018-09-04 13:55:29 -0700879status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700880 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700881 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800882 if (mPullerManager->Pull(s, &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700883 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700884 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700885 }
Yao Chena80e5c02018-09-04 13:55:29 -0700886 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700887 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700888 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700889 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700890}
891
Yao Chena80e5c02018-09-04 13:55:29 -0700892status_t StatsService::cmd_remove_all_configs(int out) {
893 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800894 VLOG("StatsService::cmd_remove_all_configs was called");
895 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800896 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800897 return NO_ERROR;
898}
899
Yao Chena80e5c02018-09-04 13:55:29 -0700900status_t StatsService::cmd_dump_memory_info(int out) {
901 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800902 return NO_ERROR;
903}
904
Yao Chena80e5c02018-09-04 13:55:29 -0700905status_t StatsService::cmd_clear_puller_cache(int out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800906 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800907 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
908 ipc->getCallingPid(), ipc->getCallingUid());
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -0800909 if (checkPermission(kPermissionDump)) {
Chenjie Yue2219202018-06-08 10:07:51 -0700910 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700911 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800912 return NO_ERROR;
913 } else {
914 return PERMISSION_DENIED;
915 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800916}
917
Yao Chena80e5c02018-09-04 13:55:29 -0700918status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Yao Chen876889c2018-05-02 11:16:16 -0700919 IPCThreadState* ipc = IPCThreadState::self();
920 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", ipc->getCallingPid(),
921 ipc->getCallingUid());
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -0800922 if (checkPermission(kPermissionDump)) {
Yao Chen876889c2018-05-02 11:16:16 -0700923 bool enabled = true;
924 if (args.size() >= 2) {
925 enabled = atoi(args[1].c_str()) != 0;
926 }
927 mProcessor->setPrintLogs(enabled);
928 return NO_ERROR;
929 } else {
930 return PERMISSION_DENIED;
931 }
932}
933
Bookatzd2386572018-12-14 15:53:14 -0800934bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800935 return getUidFromString(args[uidArgIndex].c_str(), uid);
936}
937
938bool StatsService::getUidFromString(const char* s, int32_t& uid) {
Bookatzd2386572018-12-14 15:53:14 -0800939 if (*s == '\0') {
940 return false;
941 }
942 char* endc = NULL;
943 int64_t longUid = strtol(s, &endc, 0);
944 if (*endc != '\0') {
945 return false;
946 }
947 int32_t goodUid = static_cast<int32_t>(longUid);
948 if (longUid < 0 || static_cast<uint64_t>(longUid) != static_cast<uid_t>(goodUid)) {
949 return false; // It was not of uid_t type.
950 }
951 uid = goodUid;
952
953 int32_t callingUid = IPCThreadState::self()->getCallingUid();
954 return mEngBuild // UserDebug/EngBuild are allowed to impersonate uids.
955 || (callingUid == goodUid) // Anyone can 'impersonate' themselves.
956 || (callingUid == AID_ROOT && goodUid == AID_SHELL); // ROOT can impersonate SHELL.
957}
958
Max Dashouk11e0d402019-05-16 16:58:07 -0700959Status StatsService::informAllUidData(const ParcelFileDescriptor& fd) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600960 ENFORCE_UID(AID_SYSTEM);
Max Dashouk11e0d402019-05-16 16:58:07 -0700961 // Read stream into buffer.
962 string buffer;
963 if (!android::base::ReadFdToString(fd.get(), &buffer)) {
964 return exception(Status::EX_ILLEGAL_ARGUMENT, "Failed to read all data from the pipe.");
965 }
Jeff Sharkey6b649252018-04-16 09:50:22 -0600966
Max Dashouk11e0d402019-05-16 16:58:07 -0700967 // Parse buffer.
968 UidData uidData;
969 if (!uidData.ParseFromString(buffer)) {
970 return exception(Status::EX_ILLEGAL_ARGUMENT, "Error parsing proto stream for UidData.");
971 }
David Chende701692017-10-05 13:16:02 -0700972
Max Dashouk11e0d402019-05-16 16:58:07 -0700973 vector<String16> versionStrings;
974 vector<String16> installers;
975 vector<String16> packageNames;
976 vector<int32_t> uids;
977 vector<int64_t> versions;
978
979 const auto numEntries = uidData.app_info_size();
980 versionStrings.reserve(numEntries);
981 installers.reserve(numEntries);
982 packageNames.reserve(numEntries);
983 uids.reserve(numEntries);
984 versions.reserve(numEntries);
985
986 for (const auto& appInfo: uidData.app_info()) {
987 packageNames.emplace_back(String16(appInfo.package_name().c_str()));
988 uids.push_back(appInfo.uid());
989 versions.push_back(appInfo.version());
990 versionStrings.emplace_back(String16(appInfo.version_string().c_str()));
991 installers.emplace_back(String16(appInfo.installer().c_str()));
992 }
993
994 mUidMap->updateMap(getElapsedRealtimeNs(),
995 uids,
996 versions,
997 versionStrings,
998 packageNames,
999 installers);
1000
1001 VLOG("StatsService::informAllUidData UidData proto parsed successfully.");
David Chende701692017-10-05 13:16:02 -07001002 return Status::ok();
1003}
1004
dwchen730403e2018-10-29 11:41:56 -07001005Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version,
1006 const String16& version_string, const String16& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001007 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -07001008
Jeff Sharkey6b649252018-04-16 09:50:22 -06001009 VLOG("StatsService::informOnePackage was called");
dwchen730403e2018-10-29 11:41:56 -07001010 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version, version_string, installer);
David Chende701692017-10-05 13:16:02 -07001011 return Status::ok();
1012}
1013
1014Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001015 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -07001016
Jeff Sharkey6b649252018-04-16 09:50:22 -06001017 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -07001018 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -08001019 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -07001020 return Status::ok();
1021}
1022
Yao Chenef99c4f2017-09-22 16:26:54 -07001023Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001024 ENFORCE_UID(AID_SYSTEM);
1025
yro74fed972017-11-27 14:42:42 -08001026 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -07001027 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -08001028 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
1029 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
1030 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -08001031 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -08001032 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -08001033 } else {
1034 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
1035 }
Bookatz1b0b1142017-09-08 11:58:42 -07001036 return Status::ok();
1037}
1038
Yangster-mac932ecec2018-02-01 10:23:52 -08001039Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001040 ENFORCE_UID(AID_SYSTEM);
1041
Yangster-mac932ecec2018-02-01 10:23:52 -08001042 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -07001043 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -08001044 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
1045 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
1046 if (alarmSet.size() > 0) {
1047 VLOG("Found periodic alarm fired.");
1048 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
1049 } else {
1050 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
1051 }
1052 return Status::ok();
1053}
1054
Yao Chenef99c4f2017-09-22 16:26:54 -07001055Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001056 ENFORCE_UID(AID_SYSTEM);
1057
yro74fed972017-11-27 14:42:42 -08001058 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -07001059 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -08001060 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -07001061 return Status::ok();
1062}
1063
Yao Chenef99c4f2017-09-22 16:26:54 -07001064Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001065 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001066
1067 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -08001068 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -07001069 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001070 return Status::ok();
1071}
1072
Yangster-mac892f3d32018-05-02 14:16:48 -07001073Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001074 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -07001075 VLOG("StatsService::informDeviceShutdown");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001076 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001077 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
yro947fbce2017-11-15 22:50:23 -08001078 return Status::ok();
1079}
1080
Yao Chenef99c4f2017-09-22 16:26:54 -07001081void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -07001082 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1083 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -08001084 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -07001085 statsCompanion->statsdReady();
1086 } else {
yro74fed972017-11-27 14:42:42 -08001087 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -07001088 }
1089}
1090
Yao Chenef99c4f2017-09-22 16:26:54 -07001091Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001092 ENFORCE_UID(AID_SYSTEM);
1093
yro74fed972017-11-27 14:42:42 -08001094 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -07001095 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1096 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -07001097 return Status::fromExceptionCode(
1098 Status::EX_NULL_POINTER,
1099 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -07001100 }
yro74fed972017-11-27 14:42:42 -08001101 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001102 IInterface::asBinder(statsCompanion)->linkToDeath(this);
Chenjie Yue2219202018-06-08 10:07:51 -07001103 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -08001104 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
1105 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -07001106 return Status::ok();
1107}
1108
Joe Onorato9fc9edf2017-10-15 20:08:52 -07001109void StatsService::Startup() {
1110 mConfigManager->Startup();
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001111 mProcessor->LoadActiveConfigsFromDisk();
Bookatz906a35c2017-09-20 15:26:44 -07001112}
1113
Yangster-mac97e7d202018-10-09 11:05:39 -07001114void StatsService::Terminate() {
1115 ALOGI("StatsService::Terminating");
1116 if (mProcessor != nullptr) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001117 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001118 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
Yangster-mac97e7d202018-10-09 11:05:39 -07001119 }
1120}
1121
Yao Chen0f861862019-03-27 11:51:15 -07001122// Test only interface!!!
Yao Chen3ff3a492018-08-06 16:17:37 -07001123void StatsService::OnLogEvent(LogEvent* event) {
1124 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -07001125 if (mShellSubscriber != nullptr) {
1126 mShellSubscriber->onLogEvent(*event);
1127 }
Bookatz906a35c2017-09-20 15:26:44 -07001128}
1129
Jeffrey Huang04f948b2020-01-07 10:05:25 -08001130Status StatsService::getData(int64_t key, const int32_t callingUid, vector<uint8_t>* output) {
1131 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001132
Jeffrey Huang04f948b2020-01-07 10:05:25 -08001133 VLOG("StatsService::getData with Uid %i", callingUid);
1134 ConfigKey configKey(callingUid, key);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001135 // The dump latency does not matter here since we do not include the current bucket, we do not
1136 // need to pull any new data anyhow.
David Chen56ae0d92018-05-11 16:00:22 -07001137 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001138 true /* erase_data */, GET_DATA_CALLED, FAST, output);
Bookatz4f716292018-04-10 17:15:12 -07001139 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001140}
1141
Jeffrey Huang9613a972020-01-07 10:05:03 -08001142Status StatsService::getMetadata(vector<uint8_t>* output) {
1143 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001144
Bookatz4f716292018-04-10 17:15:12 -07001145 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
1146 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -08001147}
1148
Jeff Sharkey6b649252018-04-16 09:50:22 -06001149Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001150 const int32_t callingUid) {
1151 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001152
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001153 if (addConfigurationChecked(callingUid, key, config)) {
David Chen661f7912018-01-22 17:46:24 -08001154 return Status::ok();
1155 } else {
Bookatz4f716292018-04-10 17:15:12 -07001156 ALOGE("Could not parse malformatted StatsdConfig");
1157 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
1158 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -08001159 }
1160}
1161
David Chen9fdd4032018-03-20 14:38:56 -07001162bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
1163 ConfigKey configKey(uid, key);
1164 StatsdConfig cfg;
1165 if (config.size() > 0) { // If the config is empty, skip parsing.
1166 if (!cfg.ParseFromArray(&config[0], config.size())) {
1167 return false;
1168 }
1169 }
1170 mConfigManager->UpdateConfig(configKey, cfg);
1171 return true;
1172}
1173
Jeffrey Huangad213742019-12-16 13:50:06 -08001174Status StatsService::removeDataFetchOperation(int64_t key,
1175 const int32_t callingUid) {
1176 ENFORCE_UID(AID_SYSTEM);
1177 ConfigKey configKey(callingUid, key);
Bookatz4f716292018-04-10 17:15:12 -07001178 mConfigManager->RemoveConfigReceiver(configKey);
1179 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -08001180}
1181
Jeff Sharkey6b649252018-04-16 09:50:22 -06001182Status StatsService::setDataFetchOperation(int64_t key,
Jeffrey Huangad213742019-12-16 13:50:06 -08001183 const sp<IPendingIntentRef>& pir,
1184 const int32_t callingUid) {
1185 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001186
Jeffrey Huangad213742019-12-16 13:50:06 -08001187 ConfigKey configKey(callingUid, key);
1188 mConfigManager->SetConfigReceiver(configKey, pir);
David Chen48944902018-05-03 10:29:11 -07001189 if (StorageManager::hasConfigMetricsReport(configKey)) {
1190 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
1191 configKey.ToString().c_str());
1192 mProcessor->noteOnDiskData(configKey);
1193 }
Bookatz4f716292018-04-10 17:15:12 -07001194 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001195}
1196
Jeffrey Huang47537a12020-01-06 15:35:34 -08001197Status StatsService::setActiveConfigsChangedOperation(const sp<IPendingIntentRef>& pir,
1198 const int32_t callingUid,
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001199 vector<int64_t>* output) {
Jeffrey Huang47537a12020-01-06 15:35:34 -08001200 ENFORCE_UID(AID_SYSTEM);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001201
Jeffrey Huang47537a12020-01-06 15:35:34 -08001202 mConfigManager->SetActiveConfigsChangedReceiver(callingUid, pir);
Tej Singh6ede28b2019-01-29 17:06:54 -08001203 if (output != nullptr) {
Jeffrey Huang47537a12020-01-06 15:35:34 -08001204 mProcessor->GetActiveConfigs(callingUid, *output);
Tej Singh6ede28b2019-01-29 17:06:54 -08001205 } else {
1206 ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
1207 }
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001208 return Status::ok();
1209}
1210
Jeffrey Huang47537a12020-01-06 15:35:34 -08001211Status StatsService::removeActiveConfigsChangedOperation(const int32_t callingUid) {
1212 ENFORCE_UID(AID_SYSTEM);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001213
Jeffrey Huang47537a12020-01-06 15:35:34 -08001214 mConfigManager->RemoveActiveConfigsChangedReceiver(callingUid);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001215 return Status::ok();
1216}
1217
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001218Status StatsService::removeConfiguration(int64_t key, const int32_t callingUid) {
1219 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001220
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001221 ConfigKey configKey(callingUid, key);
Bookatz4f716292018-04-10 17:15:12 -07001222 mConfigManager->RemoveConfig(configKey);
Bookatz4f716292018-04-10 17:15:12 -07001223 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001224}
1225
Bookatzc6977972018-01-16 16:55:05 -08001226Status StatsService::setBroadcastSubscriber(int64_t configId,
1227 int64_t subscriberId,
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001228 const sp<IPendingIntentRef>& pir,
1229 const int32_t callingUid) {
1230 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001231
Bookatzc6977972018-01-16 16:55:05 -08001232 VLOG("StatsService::setBroadcastSubscriber called.");
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001233 ConfigKey configKey(callingUid, configId);
Bookatz4f716292018-04-10 17:15:12 -07001234 SubscriberReporter::getInstance()
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001235 .setBroadcastSubscriber(configKey, subscriberId, pir);
Bookatz4f716292018-04-10 17:15:12 -07001236 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001237}
1238
1239Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001240 int64_t subscriberId,
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001241 const int32_t callingUid) {
1242 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001243
Bookatzc6977972018-01-16 16:55:05 -08001244 VLOG("StatsService::unsetBroadcastSubscriber called.");
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001245 ConfigKey configKey(callingUid, configId);
Bookatz4f716292018-04-10 17:15:12 -07001246 SubscriberReporter::getInstance()
1247 .unsetBroadcastSubscriber(configKey, subscriberId);
1248 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001249}
1250
yrobe6d7f92018-05-04 13:02:53 -07001251Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
1252 // Permission check not necessary as it's meant for applications to write to
1253 // statsd.
1254 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
Jeff Sharkey6bd21572019-11-15 20:45:33 -07001255 (int32_t) IPCThreadState::self()->getCallingUid(), label,
yrobe6d7f92018-05-04 13:02:53 -07001256 state);
1257 return Status::ok();
1258}
1259
Tej Singh59184292019-10-11 11:07:06 -07001260Status StatsService::registerPullAtomCallback(int32_t uid, int32_t atomTag, int64_t coolDownNs,
1261 int64_t timeoutNs, const std::vector<int32_t>& additiveFields,
1262 const sp<android::os::IPullAtomCallback>& pullerCallback) {
Tej Singh6a5c9432019-10-11 11:07:06 -07001263 ENFORCE_UID(AID_SYSTEM);
1264
Tej Singhb7802512019-12-04 17:57:04 -08001265 VLOG("StatsService::registerPullAtomCallback called.");
1266 mPullerManager->RegisterPullAtomCallback(uid, atomTag, coolDownNs, timeoutNs, additiveFields,
1267 pullerCallback);
1268 return Status::ok();
1269}
1270
1271Status StatsService::registerNativePullAtomCallback(int32_t atomTag, int64_t coolDownNs,
1272 int64_t timeoutNs, const std::vector<int32_t>& additiveFields,
1273 const sp<android::os::IPullAtomCallback>& pullerCallback) {
1274
1275 VLOG("StatsService::registerNativePullAtomCallback called.");
1276 int32_t uid = IPCThreadState::self()->getCallingUid();
Tej Singh6a5c9432019-10-11 11:07:06 -07001277 mPullerManager->RegisterPullAtomCallback(uid, atomTag, coolDownNs, timeoutNs, additiveFields,
1278 pullerCallback);
Tej Singh59184292019-10-11 11:07:06 -07001279 return Status::ok();
1280}
1281
Tej Singhfa1c1372019-12-05 20:36:54 -08001282Status StatsService::unregisterPullAtomCallback(int32_t uid, int32_t atomTag) {
1283 ENFORCE_UID(AID_SYSTEM);
1284 VLOG("StatsService::unregisterPullAtomCallback called.");
1285 mPullerManager->UnregisterPullAtomCallback(uid, atomTag);
1286 return Status::ok();
1287}
1288
Tej Singh8f358602020-01-15 16:05:39 -08001289Status StatsService::unregisterNativePullAtomCallback(int32_t atomTag) {
1290 VLOG("StatsService::unregisterNativePullAtomCallback called.");
1291 int32_t uid = IPCThreadState::self()->getCallingUid();
1292 mPullerManager->UnregisterPullAtomCallback(uid, atomTag);
1293 return Status::ok();
1294}
1295
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001296Status StatsService::getRegisteredExperimentIds(std::vector<int64_t>* experimentIdsOut) {
Jeffrey Huang80c9a972020-01-07 10:04:27 -08001297 ENFORCE_UID(AID_SYSTEM);
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001298 // TODO: add verifier permission
1299
Jonathan Nguyen703c42f2020-02-04 15:54:26 -08001300 experimentIdsOut->clear();
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001301 // Read the latest train info
Jonathan Nguyen703c42f2020-02-04 15:54:26 -08001302 vector<InstallTrainInfo> trainInfoList = StorageManager::readAllTrainInfo();
1303 if (trainInfoList.empty()) {
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001304 // No train info means no experiment IDs, return an empty list
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001305 return Status::ok();
1306 }
1307
1308 // Copy the experiment IDs to the out vector
Jonathan Nguyen703c42f2020-02-04 15:54:26 -08001309 for (InstallTrainInfo& trainInfo : trainInfoList) {
1310 experimentIdsOut->insert(experimentIdsOut->end(),
1311 trainInfo.experimentIds.begin(),
1312 trainInfo.experimentIds.end());
1313 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001314 return Status::ok();
1315}
1316
David Chen1d7b0cd2017-11-15 14:20:04 -08001317void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001318 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001319 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1320 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001321 ALOGW("Reset statsd upon system server restarts.");
Tej Singhf53d4452019-05-09 18:17:59 -07001322 int64_t systemServerRestartNs = getElapsedRealtimeNs();
1323 ProtoOutputStream proto;
1324 mProcessor->WriteActiveConfigsToProtoOutputStream(systemServerRestartNs,
1325 STATSCOMPANION_DIED, &proto);
1326
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001327 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED, FAST);
Yangster-mac892f3d32018-05-02 14:16:48 -07001328 mProcessor->resetConfigs();
Tej Singhf53d4452019-05-09 18:17:59 -07001329
1330 std::string serializedActiveConfigs;
1331 if (proto.serializeToString(&serializedActiveConfigs)) {
1332 ActiveConfigList activeConfigs;
1333 if (activeConfigs.ParseFromString(serializedActiveConfigs)) {
1334 mProcessor->SetConfigsActiveState(activeConfigs, systemServerRestartNs);
1335 }
1336 }
Yangster-mac892f3d32018-05-02 14:16:48 -07001337 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001338 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1339 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001340 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001341}
1342
Yao Chenef99c4f2017-09-22 16:26:54 -07001343} // namespace statsd
1344} // namespace os
1345} // namespace android