blob: f646f190f557b99b610df08d498400c69e5f4572 [file] [log] [blame]
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001/*
yro0feae942017-11-15 14:38:48 -08002 * Copyright (C) 2017 The Android Open Source Project
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Tej Singh484524a2018-02-01 15:10:05 -080017#define DEBUG false // STOPSHIP if true
Joe Onorato9fc9edf2017-10-15 20:08:52 -070018#include "Log.h"
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070019
20#include "StatsService.h"
Yangster-mac330af582018-02-08 15:24:38 -080021#include "stats_log_util.h"
Yao Chen8d9989b2017-11-18 18:54:50 -080022#include "android-base/stringprintf.h"
David Chenadaf8b32017-11-03 15:42:08 -070023#include "config/ConfigKey.h"
24#include "config/ConfigManager.h"
Yao Chenb3561512017-11-21 18:07:17 -080025#include "guardrail/StatsdStats.h"
yro947fbce2017-11-15 22:50:23 -080026#include "storage/StorageManager.h"
Bookatzc6977972018-01-16 16:55:05 -080027#include "subscriber/SubscriberReporter.h"
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070028
David Chen0656b7a2017-09-13 15:53:39 -070029#include <android-base/file.h>
Jeff Sharkey6b649252018-04-16 09:50:22 -060030#include <android-base/stringprintf.h>
Tej Singh53f9dee2019-04-30 17:45:54 -070031#include <android-base/strings.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Jeff Sharkey6b649252018-04-16 09:50:22 -060034#include <binder/PermissionController.h>
Chenjie Yu6b1667c2019-01-18 10:09:33 -080035#include <cutils/multiuser.h>
yro87d983c2017-11-14 21:31:43 -080036#include <dirent.h>
David Chen0656b7a2017-09-13 15:53:39 -070037#include <frameworks/base/cmds/statsd/src/statsd_config.pb.h>
Max Dashouk11e0d402019-05-16 16:58:07 -070038#include <frameworks/base/cmds/statsd/src/uid_data.pb.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070039#include <private/android_filesystem_config.h>
Bookatzb223c4e2018-02-01 15:35:04 -080040#include <statslog.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070041#include <stdio.h>
Yao Chen482d2722017-09-12 13:25:43 -070042#include <stdlib.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070043#include <sys/system_properties.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070044#include <unistd.h>
Yao Chena80e5c02018-09-04 13:55:29 -070045#include <utils/Looper.h>
46#include <utils/String16.h>
47#include <chrono>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070048
49using namespace android;
50
Jeff Sharkey6b649252018-04-16 09:50:22 -060051using android::base::StringPrintf;
Bookatzff71cad2018-09-20 17:17:49 -070052using android::util::FIELD_COUNT_REPEATED;
Chenjie Yu6b1667c2019-01-18 10:09:33 -080053using android::util::FIELD_TYPE_INT64;
Bookatzff71cad2018-09-20 17:17:49 -070054using android::util::FIELD_TYPE_MESSAGE;
Joe Onorato99598ee2019-02-11 15:55:13 +000055using android::util::ProtoReader;
Jeff Sharkey6b649252018-04-16 09:50:22 -060056
Bookatz906a35c2017-09-20 15:26:44 -070057namespace android {
58namespace os {
59namespace statsd {
60
David Chenadaf8b32017-11-03 15:42:08 -070061constexpr const char* kPermissionDump = "android.permission.DUMP";
Jeff Sharkey6b649252018-04-16 09:50:22 -060062constexpr const char* kPermissionUsage = "android.permission.PACKAGE_USAGE_STATS";
63
64constexpr const char* kOpUsage = "android:get_usage_stats";
65
yro03faf092017-12-12 00:17:50 -080066#define STATS_SERVICE_DIR "/data/misc/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070067
Bookatzff71cad2018-09-20 17:17:49 -070068// for StatsDataDumpProto
69const int FIELD_ID_REPORTS_LIST = 1;
70
Jeff Sharkey6b649252018-04-16 09:50:22 -060071static binder::Status ok() {
72 return binder::Status::ok();
73}
74
75static binder::Status exception(uint32_t code, const std::string& msg) {
76 ALOGE("%s (%d)", msg.c_str(), code);
77 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
78}
79
80binder::Status checkUid(uid_t expectedUid) {
81 uid_t uid = IPCThreadState::self()->getCallingUid();
82 if (uid == expectedUid || uid == AID_ROOT) {
83 return ok();
84 } else {
85 return exception(binder::Status::EX_SECURITY,
86 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
87 }
88}
89
90binder::Status checkDumpAndUsageStats(const String16& packageName) {
91 pid_t pid = IPCThreadState::self()->getCallingPid();
92 uid_t uid = IPCThreadState::self()->getCallingUid();
93
94 // Root, system, and shell always have access
95 if (uid == AID_ROOT || uid == AID_SYSTEM || uid == AID_SHELL) {
96 return ok();
97 }
98
99 // Caller must be granted these permissions
100 if (!checkCallingPermission(String16(kPermissionDump))) {
101 return exception(binder::Status::EX_SECURITY,
102 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionDump));
103 }
104 if (!checkCallingPermission(String16(kPermissionUsage))) {
105 return exception(binder::Status::EX_SECURITY,
106 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionUsage));
107 }
108
109 // Caller must also have usage stats op granted
110 PermissionController pc;
111 switch (pc.noteOp(String16(kOpUsage), uid, packageName)) {
112 case PermissionController::MODE_ALLOWED:
113 case PermissionController::MODE_DEFAULT:
114 return ok();
115 default:
116 return exception(binder::Status::EX_SECURITY,
117 StringPrintf("UID %d / PID %d lacks app-op %s", uid, pid, kOpUsage));
118 }
119}
120
121#define ENFORCE_UID(uid) { \
122 binder::Status status = checkUid((uid)); \
123 if (!status.isOk()) { \
124 return status; \
125 } \
126}
127
128#define ENFORCE_DUMP_AND_USAGE_STATS(packageName) { \
129 binder::Status status = checkDumpAndUsageStats(packageName); \
130 if (!status.isOk()) { \
131 return status; \
132 } \
133}
134
Yao Chen0f861862019-03-27 11:51:15 -0700135StatsService::StatsService(const sp<Looper>& handlerLooper, shared_ptr<LogEventQueue> queue)
136 : mAnomalyAlarmMonitor(new AlarmMonitor(
137 MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
138 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
139 if (sc != nullptr) {
140 sc->setAnomalyAlarm(timeMillis);
141 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
142 }
143 },
144 [](const sp<IStatsCompanionService>& sc) {
145 if (sc != nullptr) {
146 sc->cancelAnomalyAlarm();
147 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
148 }
149 })),
150 mPeriodicAlarmMonitor(new AlarmMonitor(
151 MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
152 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
153 if (sc != nullptr) {
154 sc->setAlarmForSubscriberTriggering(timeMillis);
155 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
156 }
157 },
158 [](const sp<IStatsCompanionService>& sc) {
159 if (sc != nullptr) {
160 sc->cancelAlarmForSubscriberTriggering();
161 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
162 }
163 })),
164 mEventQueue(queue) {
Yao Chen4ce07292019-02-13 13:06:36 -0800165 mUidMap = UidMap::getInstance();
Chenjie Yue2219202018-06-08 10:07:51 -0700166 mPullerManager = new StatsPullerManager();
Chenjie Yu80f91122018-01-31 20:24:50 -0800167 StatsPuller::SetUidMap(mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700168 mConfigManager = new ConfigManager();
Chenjie Yue2219202018-06-08 10:07:51 -0700169 mProcessor = new StatsLogProcessor(
170 mUidMap, mPullerManager, mAnomalyAlarmMonitor, mPeriodicAlarmMonitor,
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800171 getElapsedRealtimeNs(),
172 [this](const ConfigKey& key) {
Chenjie Yue2219202018-06-08 10:07:51 -0700173 sp<IStatsCompanionService> sc = getStatsCompanionService();
174 auto receiver = mConfigManager->GetConfigReceiver(key);
175 if (sc == nullptr) {
176 VLOG("Could not find StatsCompanionService");
177 return false;
178 } else if (receiver == nullptr) {
179 VLOG("Statscompanion could not find a broadcast receiver for %s",
180 key.ToString().c_str());
181 return false;
182 } else {
183 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
184 return true;
185 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800186 },
187 [this](const int& uid, const vector<int64_t>& activeConfigs) {
188 auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
189 sp<IStatsCompanionService> sc = getStatsCompanionService();
190 if (sc == nullptr) {
191 VLOG("Could not access statsCompanion");
192 return false;
193 } else if (receiver == nullptr) {
194 VLOG("Could not find receiver for uid %d", uid);
195 return false;
196 } else {
197 sc->sendActiveConfigsChangedBroadcast(receiver, activeConfigs);
198 VLOG("StatsService::active configs broadcast succeeded for uid %d" , uid);
199 return true;
200 }
Chenjie Yue2219202018-06-08 10:07:51 -0700201 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700202
203 mConfigManager->AddListener(mProcessor);
204
205 init_system_properties();
Yao Chen0f861862019-03-27 11:51:15 -0700206
207 if (mEventQueue != nullptr) {
208 std::thread pushedEventThread([this] { readLogs(); });
209 pushedEventThread.detach();
210 }
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700211}
212
Yao Chenef99c4f2017-09-22 16:26:54 -0700213StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700214}
215
Yao Chen0f861862019-03-27 11:51:15 -0700216/* Runs on a dedicated thread to process pushed events. */
217void StatsService::readLogs() {
218 // Read forever..... long live statsd
219 while (1) {
220 // Block until an event is available.
221 auto event = mEventQueue->waitPop();
222 // Pass it to StatsLogProcess to all configs/metrics
223 // At this point, the LogEventQueue is not blocked, so that the socketListener
224 // can read events from the socket and write to buffer to avoid data drop.
225 mProcessor->OnLogEvent(event.get());
226 // The ShellSubscriber is only used by shell for local debugging.
227 if (mShellSubscriber != nullptr) {
228 mShellSubscriber->onLogEvent(*event);
229 }
230 }
231}
232
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700233void StatsService::init_system_properties() {
234 mEngBuild = false;
235 const prop_info* buildType = __system_property_find("ro.build.type");
236 if (buildType != NULL) {
237 __system_property_read_callback(buildType, init_build_type_callback, this);
238 }
David Chen0656b7a2017-09-13 15:53:39 -0700239}
240
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700241void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
242 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700243 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700244 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
245 }
246}
247
248/**
249 * Implement our own because the default binder implementation isn't
250 * properly handling SHELL_COMMAND_TRANSACTION.
251 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700252status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
253 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700254 switch (code) {
255 case SHELL_COMMAND_TRANSACTION: {
256 int in = data.readFileDescriptor();
257 int out = data.readFileDescriptor();
258 int err = data.readFileDescriptor();
259 int argc = data.readInt32();
260 Vector<String8> args;
261 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
262 args.add(String8(data.readString16()));
263 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700264 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
265 sp<IResultReceiver> resultReceiver =
266 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700267
Yao Chena80e5c02018-09-04 13:55:29 -0700268 err = command(in, out, err, args, resultReceiver);
269 resultReceiver->send(err);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700270 return NO_ERROR;
271 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700272 default: { return BnStatsManager::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700273 }
274}
275
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700276/**
Bookatzff71cad2018-09-20 17:17:49 -0700277 * Write data from statsd.
278 * Format for statsdStats: adb shell dumpsys stats --metadata [-v] [--proto]
279 * Format for data report: adb shell dumpsys stats [anything other than --metadata] [--proto]
280 * Anything ending in --proto will be in proto format.
281 * Anything without --metadata as the first argument will be report information.
282 * (bugreports call "adb shell dumpsys stats --dump-priority NORMAL -a --proto")
283 * TODO: Come up with a more robust method of enacting <serviceutils/PriorityDumper.h>.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700284 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700285status_t StatsService::dump(int fd, const Vector<String16>& args) {
Tej Singhdd83d702018-04-10 17:24:50 -0700286 if (!checkCallingPermission(String16(kPermissionDump))) {
287 return PERMISSION_DENIED;
288 }
Bookatzff71cad2018-09-20 17:17:49 -0700289 int lastArg = args.size() - 1;
290 bool asProto = false;
291 if (lastArg >= 0 && !args[lastArg].compare(String16("--proto"))) { // last argument
292 asProto = true;
293 lastArg--;
Yao Chen884c8c12018-01-26 10:36:25 -0800294 }
Bookatzff71cad2018-09-20 17:17:49 -0700295 if (args.size() > 0 && !args[0].compare(String16("--metadata"))) { // first argument
296 // Request is to dump statsd stats.
297 bool verbose = false;
298 if (lastArg >= 0 && !args[lastArg].compare(String16("-v"))) {
299 verbose = true;
300 lastArg--;
301 }
302 dumpStatsdStats(fd, verbose, asProto);
303 } else {
304 // Request is to dump statsd report data.
305 if (asProto) {
306 dumpIncidentSection(fd);
307 } else {
308 dprintf(fd, "Non-proto format of stats data dump not available; see proto version.\n");
309 }
Tej Singh41b3f9a2018-04-03 17:06:35 -0700310 }
Yao Chen884c8c12018-01-26 10:36:25 -0800311
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700312 return NO_ERROR;
313}
314
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700315/**
Tej Singh41b3f9a2018-04-03 17:06:35 -0700316 * Write debugging data about statsd in text or proto format.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700317 */
Bookatzff71cad2018-09-20 17:17:49 -0700318void StatsService::dumpStatsdStats(int out, bool verbose, bool proto) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700319 if (proto) {
320 vector<uint8_t> data;
321 StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
322 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700323 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700324 }
325 } else {
326 StatsdStats::getInstance().dumpStats(out);
327 mProcessor->dumpStates(out, verbose);
328 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700329}
330
331/**
Bookatzff71cad2018-09-20 17:17:49 -0700332 * Write stats report data in StatsDataDumpProto incident section format.
333 */
334void StatsService::dumpIncidentSection(int out) {
335 ProtoOutputStream proto;
336 for (const ConfigKey& configKey : mConfigManager->GetAllConfigKeys()) {
337 uint64_t reportsListToken =
338 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS_LIST);
339 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
340 true /* includeCurrentBucket */, false /* erase_data */,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000341 ADB_DUMP,
342 FAST,
343 &proto);
Bookatzff71cad2018-09-20 17:17:49 -0700344 proto.end(reportsListToken);
345 proto.flush(out);
Bookatzc71d9012018-12-19 12:28:38 -0800346 proto.clear();
Bookatzff71cad2018-09-20 17:17:49 -0700347 }
348}
349
350/**
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700351 * Implementation of the adb shell cmd stats command.
352 */
Yao Chena80e5c02018-09-04 13:55:29 -0700353status_t StatsService::command(int in, int out, int err, Vector<String8>& args,
354 sp<IResultReceiver> resultReceiver) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600355 uid_t uid = IPCThreadState::self()->getCallingUid();
356 if (uid != AID_ROOT && uid != AID_SHELL) {
357 return PERMISSION_DENIED;
358 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700359
360 const int argCount = args.size();
361 if (argCount >= 1) {
362 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700363 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700364 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700365 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700366
David Chende701692017-10-05 13:16:02 -0700367 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800368 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700369 }
Yao Chen729093d2017-10-16 10:33:26 -0700370
371 if (!args[0].compare(String8("dump-report"))) {
Bookatzff71cad2018-09-20 17:17:49 -0700372 return cmd_dump_report(out, args);
Yao Chen729093d2017-10-16 10:33:26 -0700373 }
David Chen1481fe12017-10-16 13:16:34 -0700374
375 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
376 return cmd_print_pulled_metrics(out, args);
377 }
David Chenadaf8b32017-11-03 15:42:08 -0700378
379 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800380 return cmd_trigger_broadcast(out, args);
381 }
382
383 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800384 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700385 }
yro87d983c2017-11-14 21:31:43 -0800386
Yao Chen8d9989b2017-11-18 18:54:50 -0800387 if (!args[0].compare(String8("meminfo"))) {
388 return cmd_dump_memory_info(out);
389 }
yro947fbce2017-11-15 22:50:23 -0800390
391 if (!args[0].compare(String8("write-to-disk"))) {
392 return cmd_write_data_to_disk(out);
393 }
Bookatzb223c4e2018-02-01 15:35:04 -0800394
David Chen0b5c90c2018-01-25 16:51:49 -0800395 if (!args[0].compare(String8("log-app-breadcrumb"))) {
396 return cmd_log_app_breadcrumb(out, args);
Bookatzb223c4e2018-02-01 15:35:04 -0800397 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800398
Tej Singh53f9dee2019-04-30 17:45:54 -0700399 if (!args[0].compare(String8("log-binary-push"))) {
400 return cmd_log_binary_push(out, args);
401 }
402
Chenjie Yufa22d652018-02-05 14:37:48 -0800403 if (!args[0].compare(String8("clear-puller-cache"))) {
404 return cmd_clear_puller_cache(out);
405 }
Yao Chen876889c2018-05-02 11:16:16 -0700406
407 if (!args[0].compare(String8("print-logs"))) {
408 return cmd_print_logs(out, args);
409 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800410 if (!args[0].compare(String8("send-active-configs"))) {
411 return cmd_trigger_active_config_broadcast(out, args);
412 }
Yao Chena80e5c02018-09-04 13:55:29 -0700413 if (!args[0].compare(String8("data-subscribe"))) {
414 if (mShellSubscriber == nullptr) {
Yao Chen41e606c2018-10-05 15:54:11 -0700415 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
Yao Chena80e5c02018-09-04 13:55:29 -0700416 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800417 int timeoutSec = -1;
418 if (argCount >= 2) {
419 timeoutSec = atoi(args[1].c_str());
420 }
421 mShellSubscriber->startNewSubscription(in, out, resultReceiver, timeoutSec);
Yao Chena80e5c02018-09-04 13:55:29 -0700422 return NO_ERROR;
423 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700424 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700425
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700426 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700427 return NO_ERROR;
428}
429
Yao Chena80e5c02018-09-04 13:55:29 -0700430void StatsService::print_cmd_help(int out) {
431 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700432 "usage: adb shell cmd stats print-stats-log [tag_required] "
433 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700434 dprintf(out, "\n");
435 dprintf(out, "\n");
436 dprintf(out, "usage: adb shell cmd stats meminfo\n");
437 dprintf(out, "\n");
438 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
439 dprintf(out, " # adb shell stop\n");
440 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
441 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
442 dprintf(out, " # adb shell start\n");
443 dprintf(out, "\n");
444 dprintf(out, "\n");
445 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
446 dprintf(out, "\n");
447 dprintf(out, " Prints the UID, app name, version mapping.\n");
448 dprintf(out, " PKG Optional package name to print the uids of the package\n");
449 dprintf(out, "\n");
450 dprintf(out, "\n");
451 dprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
452 dprintf(out, "\n");
453 dprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
454 dprintf(out, "\n");
455 dprintf(out, "\n");
456 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
457 dprintf(out, "\n");
458 dprintf(out, " Flushes all data on memory to disk.\n");
459 dprintf(out, "\n");
460 dprintf(out, "\n");
461 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
462 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
463 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
464 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
465 dprintf(out, " uid is used.\n");
466 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
467 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
468 dprintf(out, "\n");
469 dprintf(out, "\n");
Tej Singh53f9dee2019-04-30 17:45:54 -0700470 dprintf(out,
471 "usage: adb shell cmd stats log-binary-push NAME VERSION STAGING ROLLBACK_ENABLED "
472 "LOW_LATENCY STATE EXPERIMENT_IDS\n");
473 dprintf(out, " Log a binary push state changed event.\n");
474 dprintf(out, " NAME The train name.\n");
475 dprintf(out, " VERSION The train version code.\n");
476 dprintf(out, " STAGING If this train requires a restart.\n");
477 dprintf(out, " ROLLBACK_ENABLED If rollback should be enabled for this install.\n");
478 dprintf(out, " LOW_LATENCY If the train requires low latency monitoring.\n");
479 dprintf(out, " STATE The status of the train push.\n");
480 dprintf(out, " Integer value of the enum in atoms.proto.\n");
481 dprintf(out, " EXPERIMENT_IDS Comma separated list of experiment ids.\n");
482 dprintf(out, " Leave blank for none.\n");
483 dprintf(out, "\n");
484 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700485 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
486 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
487 dprintf(out, "\n");
488 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
489 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
490 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
491 dprintf(out, "\n");
492 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
493 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
494 dprintf(out, " uid is used.\n");
495 dprintf(out, " NAME The per-uid name to use\n");
496 dprintf(out, "\n");
497 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
498 dprintf(out, "\n be removed from memory and disk!\n");
499 dprintf(out, "\n");
500 dprintf(out,
Bookatz3e906582018-12-10 17:26:58 -0800501 "usage: adb shell cmd stats dump-report [UID] NAME [--keep_data] "
502 "[--include_current_bucket] [--proto]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700503 dprintf(out, " Dump all metric data for a configuration.\n");
504 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
505 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
506 dprintf(out, " calling uid is used.\n");
507 dprintf(out, " NAME The name of the configuration\n");
Bookatz3e906582018-12-10 17:26:58 -0800508 dprintf(out, " --keep_data Do NOT erase the data upon dumping it.\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700509 dprintf(out, " --proto Print proto binary.\n");
510 dprintf(out, "\n");
511 dprintf(out, "\n");
512 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
513 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
514 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
515 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
516 dprintf(out, " calling uid is used.\n");
517 dprintf(out, " NAME The name of the configuration\n");
518 dprintf(out, "\n");
519 dprintf(out, "\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800520 dprintf(out,
521 "usage: adb shell cmd stats send-active-configs [--uid=UID] [--configs] "
522 "[NAME1] [NAME2] [NAME3..]\n");
523 dprintf(out, " Send a broadcast that informs the subscriber of the current active configs.\n");
524 dprintf(out, " --uid=UID The uid of the configurations. It is only possible to pass\n");
525 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
526 dprintf(out, " calling uid is used.\n");
527 dprintf(out, " --configs Send the list of configs in the name list instead of\n");
528 dprintf(out, " the currently active configs\n");
529 dprintf(out, " NAME LIST List of configuration names to be included in the broadcast.\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800530 dprintf(out, "\n");
531 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700532 dprintf(out, "usage: adb shell cmd stats print-stats\n");
533 dprintf(out, " Prints some basic stats.\n");
534 dprintf(out, " --proto Print proto binary instead of string format.\n");
535 dprintf(out, "\n");
536 dprintf(out, "\n");
537 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
538 dprintf(out, " Clear cached puller data.\n");
539 dprintf(out, "\n");
540 dprintf(out, "usage: adb shell cmd stats print-logs\n");
541 dprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700542}
543
Yao Chena80e5c02018-09-04 13:55:29 -0700544status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800545 string name;
546 bool good = false;
547 int uid;
548 const int argCount = args.size();
549 if (argCount == 2) {
550 // Automatically pick the UID
551 uid = IPCThreadState::self()->getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800552 name.assign(args[1].c_str(), args[1].size());
553 good = true;
554 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800555 good = getUidFromArgs(args, 1, uid);
556 if (!good) {
557 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
558 "other UIDs on eng or userdebug builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800559 }
Bookatzd2386572018-12-14 15:53:14 -0800560 name.assign(args[2].c_str(), args[2].size());
David Chen1d7b0cd2017-11-15 14:20:04 -0800561 }
562 if (!good) {
563 print_cmd_help(out);
564 return UNKNOWN_ERROR;
565 }
David Chend37bc232018-04-12 18:05:11 -0700566 ConfigKey key(uid, StrToInt64(name));
567 auto receiver = mConfigManager->GetConfigReceiver(key);
yro4d889e62017-11-17 15:44:48 -0800568 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen661f7912018-01-22 17:46:24 -0800569 if (sc == nullptr) {
570 VLOG("Could not access statsCompanion");
571 } else if (receiver == nullptr) {
572 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str())
573 } else {
David Chend37bc232018-04-12 18:05:11 -0700574 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
yro74fed972017-11-27 14:42:42 -0800575 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
576 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800577 }
578
David Chenadaf8b32017-11-03 15:42:08 -0700579 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700580}
581
Tej Singh6ede28b2019-01-29 17:06:54 -0800582status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
583 const int argCount = args.size();
584 int uid;
585 vector<int64_t> configIds;
586 if (argCount == 1) {
587 // Automatically pick the uid and send a broadcast that has no active configs.
588 uid = IPCThreadState::self()->getCallingUid();
589 mProcessor->GetActiveConfigs(uid, configIds);
590 } else {
591 int curArg = 1;
592 if(args[curArg].find("--uid=") == 0) {
593 string uidArgStr(args[curArg].c_str());
594 string uidStr = uidArgStr.substr(6);
595 if (!getUidFromString(uidStr.c_str(), uid)) {
596 dprintf(out, "Invalid UID. Note that the config can only be set for "
597 "other UIDs on eng or userdebug builds.\n");
598 return UNKNOWN_ERROR;
599 }
600 curArg++;
601 } else {
602 uid = IPCThreadState::self()->getCallingUid();
603 }
604 if (curArg == argCount || args[curArg] != "--configs") {
605 VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
606 mProcessor->GetActiveConfigs(uid, configIds);
607 } else {
608 // Flag specified, use the given list of configs.
609 curArg++;
610 for (int i = curArg; i < argCount; i++) {
611 char* endp;
612 int64_t configID = strtoll(args[i].c_str(), &endp, 10);
613 if (endp == args[i].c_str() || *endp != '\0') {
614 dprintf(out, "Error parsing config ID.\n");
615 return UNKNOWN_ERROR;
616 }
617 VLOG("Adding config id %ld", static_cast<long>(configID));
618 configIds.push_back(configID);
619 }
620 }
621 }
622 auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
623 sp<IStatsCompanionService> sc = getStatsCompanionService();
624 if (sc == nullptr) {
625 VLOG("Could not access statsCompanion");
626 } else if (receiver == nullptr) {
627 VLOG("Could not find receiver for uid %d", uid);
628 } else {
629 sc->sendActiveConfigsChangedBroadcast(receiver, configIds);
630 VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
631 }
632 return NO_ERROR;
633}
634
Yao Chena80e5c02018-09-04 13:55:29 -0700635status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700636 const int argCount = args.size();
637 if (argCount >= 2) {
638 if (args[1] == "update" || args[1] == "remove") {
639 bool good = false;
640 int uid = -1;
641 string name;
642
643 if (argCount == 3) {
644 // Automatically pick the UID
645 uid = IPCThreadState::self()->getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700646 name.assign(args[2].c_str(), args[2].size());
647 good = true;
648 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800649 good = getUidFromArgs(args, 2, uid);
650 if (!good) {
651 dprintf(err, "Invalid UID. Note that the config can only be set for "
652 "other UIDs on eng or userdebug builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700653 }
Bookatzd2386572018-12-14 15:53:14 -0800654 name.assign(args[3].c_str(), args[3].size());
yroe5f82922018-01-22 18:37:27 -0800655 } else if (argCount == 2 && args[1] == "remove") {
656 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700657 }
658
659 if (!good) {
660 // If arg parsing failed, print the help text and return an error.
661 print_cmd_help(out);
662 return UNKNOWN_ERROR;
663 }
664
665 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800666 char* endp;
667 int64_t configID = strtoll(name.c_str(), &endp, 10);
668 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700669 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800670 return UNKNOWN_ERROR;
671 }
672
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700673 // Read stream into buffer.
674 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700675 if (!android::base::ReadFdToString(in, &buffer)) {
676 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700677 return UNKNOWN_ERROR;
678 }
679
680 // Parse buffer.
681 StatsdConfig config;
682 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700683 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700684 return UNKNOWN_ERROR;
685 }
686
687 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800688 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700689 } else {
yro74fed972017-11-27 14:42:42 -0800690 if (argCount == 2) {
691 cmd_remove_all_configs(out);
692 } else {
693 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800694 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800695 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700696 }
697
698 return NO_ERROR;
699 }
David Chen0656b7a2017-09-13 15:53:39 -0700700 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700701 print_cmd_help(out);
702 return UNKNOWN_ERROR;
703}
704
Bookatzff71cad2018-09-20 17:17:49 -0700705status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700706 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800707 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700708 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800709 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700710 bool includeCurrentBucket = false;
Bookatz3e906582018-12-10 17:26:58 -0800711 bool eraseData = true;
Yao Chen729093d2017-10-16 10:33:26 -0700712 int uid;
713 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800714 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
715 proto = true;
716 argCount -= 1;
717 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700718 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
719 includeCurrentBucket = true;
720 argCount -= 1;
721 }
Bookatz3e906582018-12-10 17:26:58 -0800722 if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
723 eraseData = false;
724 argCount -= 1;
725 }
Yao Chen729093d2017-10-16 10:33:26 -0700726 if (argCount == 2) {
727 // Automatically pick the UID
728 uid = IPCThreadState::self()->getCallingUid();
Yao Chen5154a3792017-10-30 22:57:06 -0700729 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700730 good = true;
731 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800732 good = getUidFromArgs(args, 1, uid);
733 if (!good) {
734 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
735 "other UIDs on eng or userdebug builds.\n");
Yao Chen729093d2017-10-16 10:33:26 -0700736 }
Bookatzd2386572018-12-14 15:53:14 -0800737 name.assign(args[2].c_str(), args[2].size());
Yao Chen729093d2017-10-16 10:33:26 -0700738 }
739 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800740 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800741 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000742 includeCurrentBucket, eraseData, ADB_DUMP,
743 NO_TIME_CONSTRAINTS,
744 &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800745 if (proto) {
746 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700747 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800748 }
749 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700750 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800751 }
Yao Chen729093d2017-10-16 10:33:26 -0700752 return android::OK;
753 } else {
754 // If arg parsing failed, print the help text and return an error.
755 print_cmd_help(out);
756 return UNKNOWN_ERROR;
757 }
758 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700759 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700760 return UNKNOWN_ERROR;
761 }
762}
763
Yao Chena80e5c02018-09-04 13:55:29 -0700764status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700765 int argCount = args.size();
766 bool proto = false;
767 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
768 proto = true;
769 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800770 }
Yao Chenb3561512017-11-21 18:07:17 -0800771 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700772 if (proto) {
773 vector<uint8_t> data;
774 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
775 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700776 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700777 }
778
779 } else {
780 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
781 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700782 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700783 mProcessor->GetMetricsSize(key));
784 }
785 statsdStats.dumpStats(out);
786 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800787 return NO_ERROR;
788}
789
Yao Chena80e5c02018-09-04 13:55:29 -0700790status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800791 if (args.size() > 1) {
792 string pkg;
793 pkg.assign(args[1].c_str(), args[1].size());
794 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700795 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800796 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700797 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800798 }
Yao Chena80e5c02018-09-04 13:55:29 -0700799 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800800 } else {
801 mUidMap->printUidMap(out);
802 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700803 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700804}
805
Yao Chena80e5c02018-09-04 13:55:29 -0700806status_t StatsService::cmd_write_data_to_disk(int out) {
807 dprintf(out, "Writing data to disk\n");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000808 mProcessor->WriteDataToDisk(ADB_DUMP, NO_TIME_CONSTRAINTS);
yro947fbce2017-11-15 22:50:23 -0800809 return NO_ERROR;
810}
811
Yao Chena80e5c02018-09-04 13:55:29 -0700812status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800813 bool good = false;
814 int32_t uid;
815 int32_t label;
816 int32_t state;
817 const int argCount = args.size();
818 if (argCount == 3) {
819 // Automatically pick the UID
820 uid = IPCThreadState::self()->getCallingUid();
821 label = atoi(args[1].c_str());
822 state = atoi(args[2].c_str());
823 good = true;
824 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800825 good = getUidFromArgs(args, 1, uid);
826 if (!good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700827 dprintf(out,
Bookatzd2386572018-12-14 15:53:14 -0800828 "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
829 "done for other UIDs on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800830 }
Bookatzd2386572018-12-14 15:53:14 -0800831 label = atoi(args[2].c_str());
832 state = atoi(args[3].c_str());
Bookatzb223c4e2018-02-01 15:35:04 -0800833 }
834 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700835 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
David Chen0b5c90c2018-01-25 16:51:49 -0800836 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800837 } else {
838 print_cmd_help(out);
839 return UNKNOWN_ERROR;
840 }
841 return NO_ERROR;
842}
843
Tej Singh53f9dee2019-04-30 17:45:54 -0700844status_t StatsService::cmd_log_binary_push(int out, const Vector<String8>& args) {
845 // Security checks are done in the sendBinaryPushStateChanged atom.
846 const int argCount = args.size();
847 if (argCount != 7 && argCount != 8) {
848 dprintf(out, "Incorrect number of argument supplied\n");
849 return UNKNOWN_ERROR;
850 }
851 android::String16 trainName = android::String16(args[1].c_str());
852 int64_t trainVersion = strtoll(args[2].c_str(), nullptr, 10);
853 int options = 0;
854 if (args[3] == "1") {
855 options = options | IStatsManager::FLAG_REQUIRE_STAGING;
856 }
857 if (args[4] == "1") {
858 options = options | IStatsManager::FLAG_ROLLBACK_ENABLED;
859 }
860 if (args[5] == "1") {
861 options = options | IStatsManager::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
862 }
863 int32_t state = atoi(args[6].c_str());
864 vector<int64_t> experimentIds;
865 if (argCount == 8) {
866 vector<string> experimentIdsString = android::base::Split(string(args[7].c_str()), ",");
867 for (string experimentIdString : experimentIdsString) {
868 int64_t experimentId = strtoll(experimentIdString.c_str(), nullptr, 10);
869 experimentIds.push_back(experimentId);
870 }
871 }
872 dprintf(out, "Logging BinaryPushStateChanged\n");
873 sendBinaryPushStateChangedAtom(trainName, trainVersion, options, state, experimentIds);
874 return NO_ERROR;
875}
876
Yao Chena80e5c02018-09-04 13:55:29 -0700877status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700878 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700879 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800880 if (mPullerManager->Pull(s, &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700881 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700882 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700883 }
Yao Chena80e5c02018-09-04 13:55:29 -0700884 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700885 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700886 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700887 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700888}
889
Yao Chena80e5c02018-09-04 13:55:29 -0700890status_t StatsService::cmd_remove_all_configs(int out) {
891 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800892 VLOG("StatsService::cmd_remove_all_configs was called");
893 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800894 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800895 return NO_ERROR;
896}
897
Yao Chena80e5c02018-09-04 13:55:29 -0700898status_t StatsService::cmd_dump_memory_info(int out) {
899 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800900 return NO_ERROR;
901}
902
Yao Chena80e5c02018-09-04 13:55:29 -0700903status_t StatsService::cmd_clear_puller_cache(int out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800904 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800905 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
906 ipc->getCallingPid(), ipc->getCallingUid());
Chenjie Yufa22d652018-02-05 14:37:48 -0800907 if (checkCallingPermission(String16(kPermissionDump))) {
Chenjie Yue2219202018-06-08 10:07:51 -0700908 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700909 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800910 return NO_ERROR;
911 } else {
912 return PERMISSION_DENIED;
913 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800914}
915
Yao Chena80e5c02018-09-04 13:55:29 -0700916status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Yao Chen876889c2018-05-02 11:16:16 -0700917 IPCThreadState* ipc = IPCThreadState::self();
918 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", ipc->getCallingPid(),
919 ipc->getCallingUid());
920 if (checkCallingPermission(String16(kPermissionDump))) {
921 bool enabled = true;
922 if (args.size() >= 2) {
923 enabled = atoi(args[1].c_str()) != 0;
924 }
925 mProcessor->setPrintLogs(enabled);
926 return NO_ERROR;
927 } else {
928 return PERMISSION_DENIED;
929 }
930}
931
Bookatzd2386572018-12-14 15:53:14 -0800932bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800933 return getUidFromString(args[uidArgIndex].c_str(), uid);
934}
935
936bool StatsService::getUidFromString(const char* s, int32_t& uid) {
Bookatzd2386572018-12-14 15:53:14 -0800937 if (*s == '\0') {
938 return false;
939 }
940 char* endc = NULL;
941 int64_t longUid = strtol(s, &endc, 0);
942 if (*endc != '\0') {
943 return false;
944 }
945 int32_t goodUid = static_cast<int32_t>(longUid);
946 if (longUid < 0 || static_cast<uint64_t>(longUid) != static_cast<uid_t>(goodUid)) {
947 return false; // It was not of uid_t type.
948 }
949 uid = goodUid;
950
951 int32_t callingUid = IPCThreadState::self()->getCallingUid();
952 return mEngBuild // UserDebug/EngBuild are allowed to impersonate uids.
953 || (callingUid == goodUid) // Anyone can 'impersonate' themselves.
954 || (callingUid == AID_ROOT && goodUid == AID_SHELL); // ROOT can impersonate SHELL.
955}
956
Max Dashouk11e0d402019-05-16 16:58:07 -0700957Status StatsService::informAllUidData(const ParcelFileDescriptor& fd) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600958 ENFORCE_UID(AID_SYSTEM);
Max Dashouk11e0d402019-05-16 16:58:07 -0700959 // Read stream into buffer.
960 string buffer;
961 if (!android::base::ReadFdToString(fd.get(), &buffer)) {
962 return exception(Status::EX_ILLEGAL_ARGUMENT, "Failed to read all data from the pipe.");
963 }
Jeff Sharkey6b649252018-04-16 09:50:22 -0600964
Max Dashouk11e0d402019-05-16 16:58:07 -0700965 // Parse buffer.
966 UidData uidData;
967 if (!uidData.ParseFromString(buffer)) {
968 return exception(Status::EX_ILLEGAL_ARGUMENT, "Error parsing proto stream for UidData.");
969 }
David Chende701692017-10-05 13:16:02 -0700970
Max Dashouk11e0d402019-05-16 16:58:07 -0700971 vector<String16> versionStrings;
972 vector<String16> installers;
973 vector<String16> packageNames;
974 vector<int32_t> uids;
975 vector<int64_t> versions;
976
977 const auto numEntries = uidData.app_info_size();
978 versionStrings.reserve(numEntries);
979 installers.reserve(numEntries);
980 packageNames.reserve(numEntries);
981 uids.reserve(numEntries);
982 versions.reserve(numEntries);
983
984 for (const auto& appInfo: uidData.app_info()) {
985 packageNames.emplace_back(String16(appInfo.package_name().c_str()));
986 uids.push_back(appInfo.uid());
987 versions.push_back(appInfo.version());
988 versionStrings.emplace_back(String16(appInfo.version_string().c_str()));
989 installers.emplace_back(String16(appInfo.installer().c_str()));
990 }
991
992 mUidMap->updateMap(getElapsedRealtimeNs(),
993 uids,
994 versions,
995 versionStrings,
996 packageNames,
997 installers);
998
999 VLOG("StatsService::informAllUidData UidData proto parsed successfully.");
David Chende701692017-10-05 13:16:02 -07001000 return Status::ok();
1001}
1002
dwchen730403e2018-10-29 11:41:56 -07001003Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version,
1004 const String16& version_string, const String16& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001005 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -07001006
Jeff Sharkey6b649252018-04-16 09:50:22 -06001007 VLOG("StatsService::informOnePackage was called");
dwchen730403e2018-10-29 11:41:56 -07001008 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version, version_string, installer);
David Chende701692017-10-05 13:16:02 -07001009 return Status::ok();
1010}
1011
1012Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001013 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -07001014
Jeff Sharkey6b649252018-04-16 09:50:22 -06001015 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -07001016 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -08001017 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -07001018 return Status::ok();
1019}
1020
Yao Chenef99c4f2017-09-22 16:26:54 -07001021Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001022 ENFORCE_UID(AID_SYSTEM);
1023
yro74fed972017-11-27 14:42:42 -08001024 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -07001025 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -08001026 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
1027 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
1028 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -08001029 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -08001030 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -08001031 } else {
1032 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
1033 }
Bookatz1b0b1142017-09-08 11:58:42 -07001034 return Status::ok();
1035}
1036
Yangster-mac932ecec2018-02-01 10:23:52 -08001037Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001038 ENFORCE_UID(AID_SYSTEM);
1039
Yangster-mac932ecec2018-02-01 10:23:52 -08001040 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -07001041 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -08001042 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
1043 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
1044 if (alarmSet.size() > 0) {
1045 VLOG("Found periodic alarm fired.");
1046 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
1047 } else {
1048 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
1049 }
1050 return Status::ok();
1051}
1052
Yao Chenef99c4f2017-09-22 16:26:54 -07001053Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001054 ENFORCE_UID(AID_SYSTEM);
1055
yro74fed972017-11-27 14:42:42 -08001056 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -07001057 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -08001058 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -07001059 return Status::ok();
1060}
1061
Yao Chenef99c4f2017-09-22 16:26:54 -07001062Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001063 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001064
1065 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -08001066 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -07001067 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001068 return Status::ok();
1069}
1070
Yangster-mac892f3d32018-05-02 14:16:48 -07001071Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001072 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -07001073 VLOG("StatsService::informDeviceShutdown");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001074 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001075 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
yro947fbce2017-11-15 22:50:23 -08001076 return Status::ok();
1077}
1078
Yao Chenef99c4f2017-09-22 16:26:54 -07001079void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -07001080 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1081 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -08001082 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -07001083 statsCompanion->statsdReady();
1084 } else {
yro74fed972017-11-27 14:42:42 -08001085 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -07001086 }
1087}
1088
Yao Chenef99c4f2017-09-22 16:26:54 -07001089Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001090 ENFORCE_UID(AID_SYSTEM);
1091
yro74fed972017-11-27 14:42:42 -08001092 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -07001093 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1094 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -07001095 return Status::fromExceptionCode(
1096 Status::EX_NULL_POINTER,
1097 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -07001098 }
yro74fed972017-11-27 14:42:42 -08001099 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001100 IInterface::asBinder(statsCompanion)->linkToDeath(this);
Chenjie Yue2219202018-06-08 10:07:51 -07001101 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -08001102 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
1103 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -08001104 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -07001105 return Status::ok();
1106}
1107
Joe Onorato9fc9edf2017-10-15 20:08:52 -07001108void StatsService::Startup() {
1109 mConfigManager->Startup();
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001110 mProcessor->LoadActiveConfigsFromDisk();
Bookatz906a35c2017-09-20 15:26:44 -07001111}
1112
Yangster-mac97e7d202018-10-09 11:05:39 -07001113void StatsService::Terminate() {
1114 ALOGI("StatsService::Terminating");
1115 if (mProcessor != nullptr) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001116 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001117 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
Yangster-mac97e7d202018-10-09 11:05:39 -07001118 }
1119}
1120
Yao Chen0f861862019-03-27 11:51:15 -07001121// Test only interface!!!
Yao Chen3ff3a492018-08-06 16:17:37 -07001122void StatsService::OnLogEvent(LogEvent* event) {
1123 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -07001124 if (mShellSubscriber != nullptr) {
1125 mShellSubscriber->onLogEvent(*event);
1126 }
Bookatz906a35c2017-09-20 15:26:44 -07001127}
1128
Jeff Sharkey6b649252018-04-16 09:50:22 -06001129Status StatsService::getData(int64_t key, const String16& packageName, vector<uint8_t>* output) {
1130 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1131
David Chenadaf8b32017-11-03 15:42:08 -07001132 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -08001133 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001134 ConfigKey configKey(ipc->getCallingUid(), 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
Jeff Sharkey6b649252018-04-16 09:50:22 -06001142Status StatsService::getMetadata(const String16& packageName, vector<uint8_t>* output) {
1143 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1144
David Chen2e8f3802017-11-22 10:56:48 -08001145 IPCThreadState* ipc = IPCThreadState::self();
1146 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
1147 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001148 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
1149 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -08001150}
1151
Jeff Sharkey6b649252018-04-16 09:50:22 -06001152Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
1153 const String16& packageName) {
1154 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1155
David Chenadaf8b32017-11-03 15:42:08 -07001156 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -07001157 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -08001158 return Status::ok();
1159 } else {
Bookatz4f716292018-04-10 17:15:12 -07001160 ALOGE("Could not parse malformatted StatsdConfig");
1161 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
1162 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -08001163 }
1164}
1165
David Chen9fdd4032018-03-20 14:38:56 -07001166bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
1167 ConfigKey configKey(uid, key);
1168 StatsdConfig cfg;
1169 if (config.size() > 0) { // If the config is empty, skip parsing.
1170 if (!cfg.ParseFromArray(&config[0], config.size())) {
1171 return false;
1172 }
1173 }
1174 mConfigManager->UpdateConfig(configKey, cfg);
1175 return true;
1176}
1177
Jeff Sharkey6b649252018-04-16 09:50:22 -06001178Status StatsService::removeDataFetchOperation(int64_t key, const String16& packageName) {
1179 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1180
Bookatz4f716292018-04-10 17:15:12 -07001181 IPCThreadState* ipc = IPCThreadState::self();
1182 ConfigKey configKey(ipc->getCallingUid(), key);
1183 mConfigManager->RemoveConfigReceiver(configKey);
1184 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -08001185}
1186
Jeff Sharkey6b649252018-04-16 09:50:22 -06001187Status StatsService::setDataFetchOperation(int64_t key,
1188 const sp<android::IBinder>& intentSender,
1189 const String16& packageName) {
1190 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1191
Bookatz4f716292018-04-10 17:15:12 -07001192 IPCThreadState* ipc = IPCThreadState::self();
1193 ConfigKey configKey(ipc->getCallingUid(), key);
1194 mConfigManager->SetConfigReceiver(configKey, intentSender);
David Chen48944902018-05-03 10:29:11 -07001195 if (StorageManager::hasConfigMetricsReport(configKey)) {
1196 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
1197 configKey.ToString().c_str());
1198 mProcessor->noteOnDiskData(configKey);
1199 }
Bookatz4f716292018-04-10 17:15:12 -07001200 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001201}
1202
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001203Status StatsService::setActiveConfigsChangedOperation(const sp<android::IBinder>& intentSender,
1204 const String16& packageName,
1205 vector<int64_t>* output) {
1206 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1207
1208 IPCThreadState* ipc = IPCThreadState::self();
Tej Singh6ede28b2019-01-29 17:06:54 -08001209 int uid = ipc->getCallingUid();
1210 mConfigManager->SetActiveConfigsChangedReceiver(uid, intentSender);
1211 if (output != nullptr) {
1212 mProcessor->GetActiveConfigs(uid, *output);
1213 } else {
1214 ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
1215 }
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001216 return Status::ok();
1217}
1218
1219Status StatsService::removeActiveConfigsChangedOperation(const String16& packageName) {
1220 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1221
1222 IPCThreadState* ipc = IPCThreadState::self();
1223 mConfigManager->RemoveActiveConfigsChangedReceiver(ipc->getCallingUid());
1224 return Status::ok();
1225}
1226
Jeff Sharkey6b649252018-04-16 09:50:22 -06001227Status StatsService::removeConfiguration(int64_t key, const String16& packageName) {
1228 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1229
Bookatz4f716292018-04-10 17:15:12 -07001230 IPCThreadState* ipc = IPCThreadState::self();
1231 ConfigKey configKey(ipc->getCallingUid(), key);
1232 mConfigManager->RemoveConfig(configKey);
1233 SubscriberReporter::getInstance().removeConfig(configKey);
1234 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001235}
1236
Bookatzc6977972018-01-16 16:55:05 -08001237Status StatsService::setBroadcastSubscriber(int64_t configId,
1238 int64_t subscriberId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001239 const sp<android::IBinder>& intentSender,
1240 const String16& packageName) {
1241 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1242
Bookatzc6977972018-01-16 16:55:05 -08001243 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001244 IPCThreadState* ipc = IPCThreadState::self();
1245 ConfigKey configKey(ipc->getCallingUid(), configId);
1246 SubscriberReporter::getInstance()
1247 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
1248 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001249}
1250
1251Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001252 int64_t subscriberId,
1253 const String16& packageName) {
1254 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1255
Bookatzc6977972018-01-16 16:55:05 -08001256 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001257 IPCThreadState* ipc = IPCThreadState::self();
1258 ConfigKey configKey(ipc->getCallingUid(), configId);
1259 SubscriberReporter::getInstance()
1260 .unsetBroadcastSubscriber(configKey, subscriberId);
1261 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001262}
1263
yrobe6d7f92018-05-04 13:02:53 -07001264Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
1265 // Permission check not necessary as it's meant for applications to write to
1266 // statsd.
1267 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
1268 IPCThreadState::self()->getCallingUid(), label,
1269 state);
1270 return Status::ok();
1271}
1272
Tej Singha0c89dd2019-01-25 16:39:18 -08001273Status StatsService::registerPullerCallback(int32_t atomTag,
1274 const sp<android::os::IStatsPullerCallback>& pullerCallback,
1275 const String16& packageName) {
1276 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1277
1278 VLOG("StatsService::registerPullerCallback called.");
1279 mPullerManager->RegisterPullerCallback(atomTag, pullerCallback);
1280 return Status::ok();
1281}
1282
1283Status StatsService::unregisterPullerCallback(int32_t atomTag, const String16& packageName) {
1284 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1285
1286 VLOG("StatsService::unregisterPullerCallback called.");
1287 mPullerManager->UnregisterPullerCallback(atomTag);
1288 return Status::ok();
1289}
1290
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001291Status StatsService::sendBinaryPushStateChangedAtom(const android::String16& trainNameIn,
1292 const int64_t trainVersionCodeIn,
1293 const int options,
1294 const int32_t state,
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001295 const std::vector<int64_t>& experimentIdsIn) {
Tej Singh53f9dee2019-04-30 17:45:54 -07001296 // Note: We skip the usage stats op check here since we do not have a package name.
1297 // This is ok since we are overloading the usage_stats permission.
1298 // This method only sends data, it does not receive it.
1299 pid_t pid = IPCThreadState::self()->getCallingPid();
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001300 uid_t uid = IPCThreadState::self()->getCallingUid();
Tej Singh53f9dee2019-04-30 17:45:54 -07001301 // Root, system, and shell always have access
1302 if (uid != AID_ROOT && uid != AID_SYSTEM && uid != AID_SHELL) {
1303 // Caller must be granted these permissions
1304 if (!checkCallingPermission(String16(kPermissionDump))) {
1305 return exception(binder::Status::EX_SECURITY,
1306 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1307 kPermissionDump));
1308 }
1309 if (!checkCallingPermission(String16(kPermissionUsage))) {
1310 return exception(binder::Status::EX_SECURITY,
1311 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1312 kPermissionUsage));
1313 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001314 }
1315
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001316 bool readTrainInfoSuccess = false;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001317 InstallTrainInfo trainInfoOnDisk;
1318 readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfoOnDisk);
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001319
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001320 bool resetExperimentIds = false;
1321 int64_t trainVersionCode = trainVersionCodeIn;
1322 std::string trainNameUtf8 = std::string(String8(trainNameIn).string());
1323 if (readTrainInfoSuccess) {
1324 // Keep the old train version if we received an empty version.
1325 if (trainVersionCodeIn == -1) {
1326 trainVersionCode = trainInfoOnDisk.trainVersionCode;
1327 } else if (trainVersionCodeIn != trainInfoOnDisk.trainVersionCode) {
1328 // Reset experiment ids if we receive a new non-empty train version.
1329 resetExperimentIds = true;
1330 }
1331
1332 // Keep the old train name if we received an empty train name.
1333 if (trainNameUtf8.size() == 0) {
1334 trainNameUtf8 = trainInfoOnDisk.trainName;
1335 } else if (trainNameUtf8 != trainInfoOnDisk.trainName) {
1336 // Reset experiment ids if we received a new valid train name.
1337 resetExperimentIds = true;
1338 }
1339
1340 // Reset if we received a different experiment id.
1341 if (!experimentIdsIn.empty() &&
1342 (trainInfoOnDisk.experimentIds.empty() ||
1343 experimentIdsIn[0] != trainInfoOnDisk.experimentIds[0])) {
1344 resetExperimentIds = true;
1345 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001346 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001347
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001348 // Find the right experiment IDs
1349 std::vector<int64_t> experimentIds;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001350 if (resetExperimentIds || !readTrainInfoSuccess) {
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001351 experimentIds = experimentIdsIn;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001352 } else {
1353 experimentIds = trainInfoOnDisk.experimentIds;
1354 }
1355
1356 if (!experimentIds.empty()) {
1357 int64_t firstId = experimentIds[0];
1358 switch (state) {
1359 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALL_SUCCESS:
1360 experimentIds.push_back(firstId + 1);
1361 break;
1362 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_INITIATED:
1363 experimentIds.push_back(firstId + 2);
1364 break;
1365 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_SUCCESS:
1366 experimentIds.push_back(firstId + 3);
1367 break;
1368 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001369 }
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001370
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001371 // Flatten the experiment IDs to proto
1372 vector<uint8_t> experimentIdsProtoBuffer;
1373 writeExperimentIdsToProto(experimentIds, &experimentIdsProtoBuffer);
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001374 StorageManager::writeTrainInfo(trainVersionCode, trainNameUtf8, state, experimentIds);
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001375
1376 userid_t userId = multiuser_get_user_id(uid);
1377 bool requiresStaging = options & IStatsManager::FLAG_REQUIRE_STAGING;
1378 bool rollbackEnabled = options & IStatsManager::FLAG_ROLLBACK_ENABLED;
1379 bool requiresLowLatencyMonitor = options & IStatsManager::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001380 LogEvent event(trainNameUtf8, trainVersionCode, requiresStaging, rollbackEnabled,
1381 requiresLowLatencyMonitor, state, experimentIdsProtoBuffer, userId);
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001382 mProcessor->OnLogEvent(&event);
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001383 return Status::ok();
1384}
1385
1386Status StatsService::getRegisteredExperimentIds(std::vector<int64_t>* experimentIdsOut) {
1387 uid_t uid = IPCThreadState::self()->getCallingUid();
1388
1389 // Caller must be granted these permissions
1390 if (!checkCallingPermission(String16(kPermissionDump))) {
1391 return exception(binder::Status::EX_SECURITY,
1392 StringPrintf("UID %d lacks permission %s", uid, kPermissionDump));
1393 }
1394 if (!checkCallingPermission(String16(kPermissionUsage))) {
1395 return exception(binder::Status::EX_SECURITY,
1396 StringPrintf("UID %d lacks permission %s", uid, kPermissionUsage));
1397 }
1398 // TODO: add verifier permission
1399
1400 // Read the latest train info
1401 InstallTrainInfo trainInfo;
1402 if (!StorageManager::readTrainInfo(trainInfo)) {
1403 // No train info means no experiment IDs, return an empty list
1404 experimentIdsOut->clear();
1405 return Status::ok();
1406 }
1407
1408 // Copy the experiment IDs to the out vector
1409 experimentIdsOut->assign(trainInfo.experimentIds.begin(), trainInfo.experimentIds.end());
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001410 return Status::ok();
1411}
1412
Howard Roa46b6582018-09-18 16:45:02 -07001413hardware::Return<void> StatsService::reportSpeakerImpedance(
1414 const SpeakerImpedance& speakerImpedance) {
Tej Singh8928ed72019-02-22 19:06:22 -08001415 android::util::stats_write(android::util::SPEAKER_IMPEDANCE_REPORTED,
1416 speakerImpedance.speakerLocation, speakerImpedance.milliOhms);
Howard Roa46b6582018-09-18 16:45:02 -07001417
1418 return hardware::Void();
1419}
1420
1421hardware::Return<void> StatsService::reportHardwareFailed(const HardwareFailed& hardwareFailed) {
Tej Singh8928ed72019-02-22 19:06:22 -08001422 android::util::stats_write(android::util::HARDWARE_FAILED, int32_t(hardwareFailed.hardwareType),
1423 hardwareFailed.hardwareLocation, int32_t(hardwareFailed.errorCode));
Howard Roa46b6582018-09-18 16:45:02 -07001424
1425 return hardware::Void();
1426}
1427
1428hardware::Return<void> StatsService::reportPhysicalDropDetected(
1429 const PhysicalDropDetected& physicalDropDetected) {
Tej Singh8928ed72019-02-22 19:06:22 -08001430 android::util::stats_write(android::util::PHYSICAL_DROP_DETECTED,
1431 int32_t(physicalDropDetected.confidencePctg), physicalDropDetected.accelPeak,
1432 physicalDropDetected.freefallDuration);
Howard Roa46b6582018-09-18 16:45:02 -07001433
1434 return hardware::Void();
1435}
1436
1437hardware::Return<void> StatsService::reportChargeCycles(const ChargeCycles& chargeCycles) {
Tej Singh8928ed72019-02-22 19:06:22 -08001438 std::vector<int32_t> buckets = chargeCycles.cycleBucket;
1439 int initialSize = buckets.size();
1440 for (int i = 0; i < 10 - initialSize; i++) {
1441 buckets.push_back(-1); // Push -1 for buckets that do not exist.
1442 }
1443 android::util::stats_write(android::util::CHARGE_CYCLES_REPORTED, buckets[0], buckets[1],
1444 buckets[2], buckets[3], buckets[4], buckets[5], buckets[6], buckets[7], buckets[8],
1445 buckets[9]);
Howard Roa46b6582018-09-18 16:45:02 -07001446
1447 return hardware::Void();
1448}
1449
1450hardware::Return<void> StatsService::reportBatteryHealthSnapshot(
1451 const BatteryHealthSnapshotArgs& batteryHealthSnapshotArgs) {
Tej Singh8928ed72019-02-22 19:06:22 -08001452 android::util::stats_write(android::util::BATTERY_HEALTH_SNAPSHOT,
1453 int32_t(batteryHealthSnapshotArgs.type), batteryHealthSnapshotArgs.temperatureDeciC,
1454 batteryHealthSnapshotArgs.voltageMicroV, batteryHealthSnapshotArgs.currentMicroA,
1455 batteryHealthSnapshotArgs.openCircuitVoltageMicroV,
1456 batteryHealthSnapshotArgs.resistanceMicroOhm, batteryHealthSnapshotArgs.levelPercent);
Howard Roa46b6582018-09-18 16:45:02 -07001457
1458 return hardware::Void();
1459}
1460
1461hardware::Return<void> StatsService::reportSlowIo(const SlowIo& slowIo) {
Tej Singh8928ed72019-02-22 19:06:22 -08001462 android::util::stats_write(android::util::SLOW_IO, int32_t(slowIo.operation), slowIo.count);
Howard Roa46b6582018-09-18 16:45:02 -07001463
1464 return hardware::Void();
1465}
1466
1467hardware::Return<void> StatsService::reportBatteryCausedShutdown(
1468 const BatteryCausedShutdown& batteryCausedShutdown) {
Tej Singh8928ed72019-02-22 19:06:22 -08001469 android::util::stats_write(android::util::BATTERY_CAUSED_SHUTDOWN,
1470 batteryCausedShutdown.voltageMicroV);
Howard Roa46b6582018-09-18 16:45:02 -07001471
1472 return hardware::Void();
1473}
1474
Maggie Whitefc1aa592018-11-28 21:55:23 -08001475hardware::Return<void> StatsService::reportUsbPortOverheatEvent(
1476 const UsbPortOverheatEvent& usbPortOverheatEvent) {
Tej Singh8928ed72019-02-22 19:06:22 -08001477 android::util::stats_write(android::util::USB_PORT_OVERHEAT_EVENT_REPORTED,
1478 usbPortOverheatEvent.plugTemperatureDeciC, usbPortOverheatEvent.maxTemperatureDeciC,
1479 usbPortOverheatEvent.timeToOverheat, usbPortOverheatEvent.timeToHysteresis,
1480 usbPortOverheatEvent.timeToInactive);
Maggie Whitefc1aa592018-11-28 21:55:23 -08001481
1482 return hardware::Void();
1483}
1484
Carter Hsub8fd1e92019-01-11 15:24:45 +08001485hardware::Return<void> StatsService::reportSpeechDspStat(
1486 const SpeechDspStat& speechDspStat) {
Tej Singh8928ed72019-02-22 19:06:22 -08001487 android::util::stats_write(android::util::SPEECH_DSP_STAT_REPORTED,
1488 speechDspStat.totalUptimeMillis, speechDspStat.totalDowntimeMillis,
1489 speechDspStat.totalCrashCount, speechDspStat.totalRecoverCount);
Carter Hsub8fd1e92019-01-11 15:24:45 +08001490
1491 return hardware::Void();
1492}
1493
Maggie White58174da2019-01-18 15:23:35 -08001494hardware::Return<void> StatsService::reportVendorAtom(const VendorAtom& vendorAtom) {
1495 std::string reverseDomainName = (std::string) vendorAtom.reverseDomainName;
1496 if (vendorAtom.atomId < 100000 || vendorAtom.atomId >= 200000) {
1497 ALOGE("Atom ID %ld is not a valid vendor atom ID", (long) vendorAtom.atomId);
1498 return hardware::Void();
1499 }
1500 if (reverseDomainName.length() > 50) {
1501 ALOGE("Vendor atom reverse domain name %s is too long.", reverseDomainName.c_str());
1502 return hardware::Void();
1503 }
1504 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), vendorAtom);
1505 mProcessor->OnLogEvent(&event);
1506
1507 return hardware::Void();
1508}
1509
David Chen1d7b0cd2017-11-15 14:20:04 -08001510void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001511 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001512 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1513 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001514 ALOGW("Reset statsd upon system server restarts.");
Tej Singhf53d4452019-05-09 18:17:59 -07001515 int64_t systemServerRestartNs = getElapsedRealtimeNs();
1516 ProtoOutputStream proto;
1517 mProcessor->WriteActiveConfigsToProtoOutputStream(systemServerRestartNs,
1518 STATSCOMPANION_DIED, &proto);
1519
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001520 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED, FAST);
Yangster-mac892f3d32018-05-02 14:16:48 -07001521 mProcessor->resetConfigs();
Tej Singhf53d4452019-05-09 18:17:59 -07001522
1523 std::string serializedActiveConfigs;
1524 if (proto.serializeToString(&serializedActiveConfigs)) {
1525 ActiveConfigList activeConfigs;
1526 if (activeConfigs.ParseFromString(serializedActiveConfigs)) {
1527 mProcessor->SetConfigsActiveState(activeConfigs, systemServerRestartNs);
1528 }
1529 }
Yangster-mac892f3d32018-05-02 14:16:48 -07001530 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001531 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1532 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
1533 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001534 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001535}
1536
Yao Chenef99c4f2017-09-22 16:26:54 -07001537} // namespace statsd
1538} // namespace os
1539} // namespace android