blob: dd651552929a1a3bdb588f00357804e28a5d4fdb [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
Tej Singh051001c2019-11-14 11:59:48 -0800203 mUidMap->setListener(mProcessor);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700204 mConfigManager->AddListener(mProcessor);
205
206 init_system_properties();
Yao Chen0f861862019-03-27 11:51:15 -0700207
208 if (mEventQueue != nullptr) {
209 std::thread pushedEventThread([this] { readLogs(); });
210 pushedEventThread.detach();
211 }
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700212}
213
Yao Chenef99c4f2017-09-22 16:26:54 -0700214StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700215}
216
Yao Chen0f861862019-03-27 11:51:15 -0700217/* Runs on a dedicated thread to process pushed events. */
218void StatsService::readLogs() {
219 // Read forever..... long live statsd
220 while (1) {
221 // Block until an event is available.
222 auto event = mEventQueue->waitPop();
223 // Pass it to StatsLogProcess to all configs/metrics
224 // At this point, the LogEventQueue is not blocked, so that the socketListener
225 // can read events from the socket and write to buffer to avoid data drop.
226 mProcessor->OnLogEvent(event.get());
227 // The ShellSubscriber is only used by shell for local debugging.
228 if (mShellSubscriber != nullptr) {
229 mShellSubscriber->onLogEvent(*event);
230 }
231 }
232}
233
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700234void StatsService::init_system_properties() {
235 mEngBuild = false;
236 const prop_info* buildType = __system_property_find("ro.build.type");
237 if (buildType != NULL) {
238 __system_property_read_callback(buildType, init_build_type_callback, this);
239 }
David Chen0656b7a2017-09-13 15:53:39 -0700240}
241
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700242void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
243 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700244 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700245 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
246 }
247}
248
249/**
250 * Implement our own because the default binder implementation isn't
251 * properly handling SHELL_COMMAND_TRANSACTION.
252 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700253status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
254 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700255 switch (code) {
256 case SHELL_COMMAND_TRANSACTION: {
257 int in = data.readFileDescriptor();
258 int out = data.readFileDescriptor();
259 int err = data.readFileDescriptor();
260 int argc = data.readInt32();
261 Vector<String8> args;
262 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
263 args.add(String8(data.readString16()));
264 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700265 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
266 sp<IResultReceiver> resultReceiver =
267 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700268
Yao Chena80e5c02018-09-04 13:55:29 -0700269 err = command(in, out, err, args, resultReceiver);
270 resultReceiver->send(err);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700271 return NO_ERROR;
272 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700273 default: { return BnStatsManager::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) {
Tej Singhdd83d702018-04-10 17:24:50 -0700287 if (!checkCallingPermission(String16(kPermissionDump))) {
288 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"))) {
415 if (mShellSubscriber == nullptr) {
Yao Chen41e606c2018-10-05 15:54:11 -0700416 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
Yao Chena80e5c02018-09-04 13:55:29 -0700417 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800418 int timeoutSec = -1;
419 if (argCount >= 2) {
420 timeoutSec = atoi(args[1].c_str());
421 }
422 mShellSubscriber->startNewSubscription(in, out, resultReceiver, timeoutSec);
Yao Chena80e5c02018-09-04 13:55:29 -0700423 return NO_ERROR;
424 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700425 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700426
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700427 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700428 return NO_ERROR;
429}
430
Yao Chena80e5c02018-09-04 13:55:29 -0700431void StatsService::print_cmd_help(int out) {
432 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700433 "usage: adb shell cmd stats print-stats-log [tag_required] "
434 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700435 dprintf(out, "\n");
436 dprintf(out, "\n");
437 dprintf(out, "usage: adb shell cmd stats meminfo\n");
438 dprintf(out, "\n");
439 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
440 dprintf(out, " # adb shell stop\n");
441 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
442 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
443 dprintf(out, " # adb shell start\n");
444 dprintf(out, "\n");
445 dprintf(out, "\n");
446 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
447 dprintf(out, "\n");
448 dprintf(out, " Prints the UID, app name, version mapping.\n");
449 dprintf(out, " PKG Optional package name to print the uids of the package\n");
450 dprintf(out, "\n");
451 dprintf(out, "\n");
452 dprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
453 dprintf(out, "\n");
454 dprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
455 dprintf(out, "\n");
456 dprintf(out, "\n");
457 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
458 dprintf(out, "\n");
459 dprintf(out, " Flushes all data on memory to disk.\n");
460 dprintf(out, "\n");
461 dprintf(out, "\n");
462 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
463 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
464 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
465 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
466 dprintf(out, " uid is used.\n");
467 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
468 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
469 dprintf(out, "\n");
470 dprintf(out, "\n");
Tej Singh53f9dee2019-04-30 17:45:54 -0700471 dprintf(out,
472 "usage: adb shell cmd stats log-binary-push NAME VERSION STAGING ROLLBACK_ENABLED "
473 "LOW_LATENCY STATE EXPERIMENT_IDS\n");
474 dprintf(out, " Log a binary push state changed event.\n");
475 dprintf(out, " NAME The train name.\n");
476 dprintf(out, " VERSION The train version code.\n");
477 dprintf(out, " STAGING If this train requires a restart.\n");
478 dprintf(out, " ROLLBACK_ENABLED If rollback should be enabled for this install.\n");
479 dprintf(out, " LOW_LATENCY If the train requires low latency monitoring.\n");
480 dprintf(out, " STATE The status of the train push.\n");
481 dprintf(out, " Integer value of the enum in atoms.proto.\n");
482 dprintf(out, " EXPERIMENT_IDS Comma separated list of experiment ids.\n");
483 dprintf(out, " Leave blank for none.\n");
484 dprintf(out, "\n");
485 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700486 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
487 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
488 dprintf(out, "\n");
489 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
490 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
491 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
492 dprintf(out, "\n");
493 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
494 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
495 dprintf(out, " uid is used.\n");
496 dprintf(out, " NAME The per-uid name to use\n");
497 dprintf(out, "\n");
498 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
499 dprintf(out, "\n be removed from memory and disk!\n");
500 dprintf(out, "\n");
501 dprintf(out,
Bookatz3e906582018-12-10 17:26:58 -0800502 "usage: adb shell cmd stats dump-report [UID] NAME [--keep_data] "
503 "[--include_current_bucket] [--proto]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700504 dprintf(out, " Dump all metric data for a configuration.\n");
505 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
506 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
507 dprintf(out, " calling uid is used.\n");
508 dprintf(out, " NAME The name of the configuration\n");
Bookatz3e906582018-12-10 17:26:58 -0800509 dprintf(out, " --keep_data Do NOT erase the data upon dumping it.\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700510 dprintf(out, " --proto Print proto binary.\n");
511 dprintf(out, "\n");
512 dprintf(out, "\n");
513 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
514 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
515 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
516 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
517 dprintf(out, " calling uid is used.\n");
518 dprintf(out, " NAME The name of the configuration\n");
519 dprintf(out, "\n");
520 dprintf(out, "\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800521 dprintf(out,
522 "usage: adb shell cmd stats send-active-configs [--uid=UID] [--configs] "
523 "[NAME1] [NAME2] [NAME3..]\n");
524 dprintf(out, " Send a broadcast that informs the subscriber of the current active configs.\n");
525 dprintf(out, " --uid=UID The uid of the configurations. It is only possible to pass\n");
526 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
527 dprintf(out, " calling uid is used.\n");
528 dprintf(out, " --configs Send the list of configs in the name list instead of\n");
529 dprintf(out, " the currently active configs\n");
530 dprintf(out, " NAME LIST List of configuration names to be included in the broadcast.\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800531 dprintf(out, "\n");
532 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700533 dprintf(out, "usage: adb shell cmd stats print-stats\n");
534 dprintf(out, " Prints some basic stats.\n");
535 dprintf(out, " --proto Print proto binary instead of string format.\n");
536 dprintf(out, "\n");
537 dprintf(out, "\n");
538 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
539 dprintf(out, " Clear cached puller data.\n");
540 dprintf(out, "\n");
541 dprintf(out, "usage: adb shell cmd stats print-logs\n");
542 dprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700543}
544
Yao Chena80e5c02018-09-04 13:55:29 -0700545status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800546 string name;
547 bool good = false;
548 int uid;
549 const int argCount = args.size();
550 if (argCount == 2) {
551 // Automatically pick the UID
552 uid = IPCThreadState::self()->getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800553 name.assign(args[1].c_str(), args[1].size());
554 good = true;
555 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800556 good = getUidFromArgs(args, 1, uid);
557 if (!good) {
558 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
559 "other UIDs on eng or userdebug builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800560 }
Bookatzd2386572018-12-14 15:53:14 -0800561 name.assign(args[2].c_str(), args[2].size());
David Chen1d7b0cd2017-11-15 14:20:04 -0800562 }
563 if (!good) {
564 print_cmd_help(out);
565 return UNKNOWN_ERROR;
566 }
David Chend37bc232018-04-12 18:05:11 -0700567 ConfigKey key(uid, StrToInt64(name));
568 auto receiver = mConfigManager->GetConfigReceiver(key);
yro4d889e62017-11-17 15:44:48 -0800569 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen661f7912018-01-22 17:46:24 -0800570 if (sc == nullptr) {
571 VLOG("Could not access statsCompanion");
572 } else if (receiver == nullptr) {
573 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str())
574 } else {
David Chend37bc232018-04-12 18:05:11 -0700575 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
yro74fed972017-11-27 14:42:42 -0800576 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
577 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800578 }
579
David Chenadaf8b32017-11-03 15:42:08 -0700580 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700581}
582
Tej Singh6ede28b2019-01-29 17:06:54 -0800583status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
584 const int argCount = args.size();
585 int uid;
586 vector<int64_t> configIds;
587 if (argCount == 1) {
588 // Automatically pick the uid and send a broadcast that has no active configs.
589 uid = IPCThreadState::self()->getCallingUid();
590 mProcessor->GetActiveConfigs(uid, configIds);
591 } else {
592 int curArg = 1;
593 if(args[curArg].find("--uid=") == 0) {
594 string uidArgStr(args[curArg].c_str());
595 string uidStr = uidArgStr.substr(6);
596 if (!getUidFromString(uidStr.c_str(), uid)) {
597 dprintf(out, "Invalid UID. Note that the config can only be set for "
598 "other UIDs on eng or userdebug builds.\n");
599 return UNKNOWN_ERROR;
600 }
601 curArg++;
602 } else {
603 uid = IPCThreadState::self()->getCallingUid();
604 }
605 if (curArg == argCount || args[curArg] != "--configs") {
606 VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
607 mProcessor->GetActiveConfigs(uid, configIds);
608 } else {
609 // Flag specified, use the given list of configs.
610 curArg++;
611 for (int i = curArg; i < argCount; i++) {
612 char* endp;
613 int64_t configID = strtoll(args[i].c_str(), &endp, 10);
614 if (endp == args[i].c_str() || *endp != '\0') {
615 dprintf(out, "Error parsing config ID.\n");
616 return UNKNOWN_ERROR;
617 }
618 VLOG("Adding config id %ld", static_cast<long>(configID));
619 configIds.push_back(configID);
620 }
621 }
622 }
623 auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
624 sp<IStatsCompanionService> sc = getStatsCompanionService();
625 if (sc == nullptr) {
626 VLOG("Could not access statsCompanion");
627 } else if (receiver == nullptr) {
628 VLOG("Could not find receiver for uid %d", uid);
629 } else {
630 sc->sendActiveConfigsChangedBroadcast(receiver, configIds);
631 VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
632 }
633 return NO_ERROR;
634}
635
Yao Chena80e5c02018-09-04 13:55:29 -0700636status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700637 const int argCount = args.size();
638 if (argCount >= 2) {
639 if (args[1] == "update" || args[1] == "remove") {
640 bool good = false;
641 int uid = -1;
642 string name;
643
644 if (argCount == 3) {
645 // Automatically pick the UID
646 uid = IPCThreadState::self()->getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700647 name.assign(args[2].c_str(), args[2].size());
648 good = true;
649 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800650 good = getUidFromArgs(args, 2, uid);
651 if (!good) {
652 dprintf(err, "Invalid UID. Note that the config can only be set for "
653 "other UIDs on eng or userdebug builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700654 }
Bookatzd2386572018-12-14 15:53:14 -0800655 name.assign(args[3].c_str(), args[3].size());
yroe5f82922018-01-22 18:37:27 -0800656 } else if (argCount == 2 && args[1] == "remove") {
657 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700658 }
659
660 if (!good) {
661 // If arg parsing failed, print the help text and return an error.
662 print_cmd_help(out);
663 return UNKNOWN_ERROR;
664 }
665
666 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800667 char* endp;
668 int64_t configID = strtoll(name.c_str(), &endp, 10);
669 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700670 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800671 return UNKNOWN_ERROR;
672 }
673
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700674 // Read stream into buffer.
675 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700676 if (!android::base::ReadFdToString(in, &buffer)) {
677 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700678 return UNKNOWN_ERROR;
679 }
680
681 // Parse buffer.
682 StatsdConfig config;
683 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700684 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700685 return UNKNOWN_ERROR;
686 }
687
688 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800689 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700690 } else {
yro74fed972017-11-27 14:42:42 -0800691 if (argCount == 2) {
692 cmd_remove_all_configs(out);
693 } else {
694 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800695 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800696 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700697 }
698
699 return NO_ERROR;
700 }
David Chen0656b7a2017-09-13 15:53:39 -0700701 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700702 print_cmd_help(out);
703 return UNKNOWN_ERROR;
704}
705
Bookatzff71cad2018-09-20 17:17:49 -0700706status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700707 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800708 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700709 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800710 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700711 bool includeCurrentBucket = false;
Bookatz3e906582018-12-10 17:26:58 -0800712 bool eraseData = true;
Yao Chen729093d2017-10-16 10:33:26 -0700713 int uid;
714 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800715 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
716 proto = true;
717 argCount -= 1;
718 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700719 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
720 includeCurrentBucket = true;
721 argCount -= 1;
722 }
Bookatz3e906582018-12-10 17:26:58 -0800723 if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
724 eraseData = false;
725 argCount -= 1;
726 }
Yao Chen729093d2017-10-16 10:33:26 -0700727 if (argCount == 2) {
728 // Automatically pick the UID
729 uid = IPCThreadState::self()->getCallingUid();
Yao Chen5154a3792017-10-30 22:57:06 -0700730 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700731 good = true;
732 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800733 good = getUidFromArgs(args, 1, uid);
734 if (!good) {
735 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
736 "other UIDs on eng or userdebug builds.\n");
Yao Chen729093d2017-10-16 10:33:26 -0700737 }
Bookatzd2386572018-12-14 15:53:14 -0800738 name.assign(args[2].c_str(), args[2].size());
Yao Chen729093d2017-10-16 10:33:26 -0700739 }
740 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800741 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800742 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000743 includeCurrentBucket, eraseData, ADB_DUMP,
744 NO_TIME_CONSTRAINTS,
745 &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800746 if (proto) {
747 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700748 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800749 }
750 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700751 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800752 }
Yao Chen729093d2017-10-16 10:33:26 -0700753 return android::OK;
754 } else {
755 // If arg parsing failed, print the help text and return an error.
756 print_cmd_help(out);
757 return UNKNOWN_ERROR;
758 }
759 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700760 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700761 return UNKNOWN_ERROR;
762 }
763}
764
Yao Chena80e5c02018-09-04 13:55:29 -0700765status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700766 int argCount = args.size();
767 bool proto = false;
768 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
769 proto = true;
770 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800771 }
Yao Chenb3561512017-11-21 18:07:17 -0800772 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700773 if (proto) {
774 vector<uint8_t> data;
775 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
776 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700777 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700778 }
779
780 } else {
781 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
782 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700783 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700784 mProcessor->GetMetricsSize(key));
785 }
786 statsdStats.dumpStats(out);
787 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800788 return NO_ERROR;
789}
790
Yao Chena80e5c02018-09-04 13:55:29 -0700791status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800792 if (args.size() > 1) {
793 string pkg;
794 pkg.assign(args[1].c_str(), args[1].size());
795 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700796 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800797 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700798 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800799 }
Yao Chena80e5c02018-09-04 13:55:29 -0700800 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800801 } else {
802 mUidMap->printUidMap(out);
803 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700804 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700805}
806
Yao Chena80e5c02018-09-04 13:55:29 -0700807status_t StatsService::cmd_write_data_to_disk(int out) {
808 dprintf(out, "Writing data to disk\n");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000809 mProcessor->WriteDataToDisk(ADB_DUMP, NO_TIME_CONSTRAINTS);
yro947fbce2017-11-15 22:50:23 -0800810 return NO_ERROR;
811}
812
Yao Chena80e5c02018-09-04 13:55:29 -0700813status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800814 bool good = false;
815 int32_t uid;
816 int32_t label;
817 int32_t state;
818 const int argCount = args.size();
819 if (argCount == 3) {
820 // Automatically pick the UID
821 uid = IPCThreadState::self()->getCallingUid();
822 label = atoi(args[1].c_str());
823 state = atoi(args[2].c_str());
824 good = true;
825 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800826 good = getUidFromArgs(args, 1, uid);
827 if (!good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700828 dprintf(out,
Bookatzd2386572018-12-14 15:53:14 -0800829 "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
830 "done for other UIDs on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800831 }
Bookatzd2386572018-12-14 15:53:14 -0800832 label = atoi(args[2].c_str());
833 state = atoi(args[3].c_str());
Bookatzb223c4e2018-02-01 15:35:04 -0800834 }
835 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700836 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
David Chen0b5c90c2018-01-25 16:51:49 -0800837 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800838 } else {
839 print_cmd_help(out);
840 return UNKNOWN_ERROR;
841 }
842 return NO_ERROR;
843}
844
Tej Singh53f9dee2019-04-30 17:45:54 -0700845status_t StatsService::cmd_log_binary_push(int out, const Vector<String8>& args) {
846 // Security checks are done in the sendBinaryPushStateChanged atom.
847 const int argCount = args.size();
848 if (argCount != 7 && argCount != 8) {
849 dprintf(out, "Incorrect number of argument supplied\n");
850 return UNKNOWN_ERROR;
851 }
852 android::String16 trainName = android::String16(args[1].c_str());
853 int64_t trainVersion = strtoll(args[2].c_str(), nullptr, 10);
854 int options = 0;
855 if (args[3] == "1") {
856 options = options | IStatsManager::FLAG_REQUIRE_STAGING;
857 }
858 if (args[4] == "1") {
859 options = options | IStatsManager::FLAG_ROLLBACK_ENABLED;
860 }
861 if (args[5] == "1") {
862 options = options | IStatsManager::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
863 }
864 int32_t state = atoi(args[6].c_str());
865 vector<int64_t> experimentIds;
866 if (argCount == 8) {
867 vector<string> experimentIdsString = android::base::Split(string(args[7].c_str()), ",");
868 for (string experimentIdString : experimentIdsString) {
869 int64_t experimentId = strtoll(experimentIdString.c_str(), nullptr, 10);
870 experimentIds.push_back(experimentId);
871 }
872 }
873 dprintf(out, "Logging BinaryPushStateChanged\n");
874 sendBinaryPushStateChangedAtom(trainName, trainVersion, options, state, experimentIds);
875 return NO_ERROR;
876}
877
Yao Chena80e5c02018-09-04 13:55:29 -0700878status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700879 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700880 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800881 if (mPullerManager->Pull(s, &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700882 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700883 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700884 }
Yao Chena80e5c02018-09-04 13:55:29 -0700885 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700886 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700887 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700888 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700889}
890
Yao Chena80e5c02018-09-04 13:55:29 -0700891status_t StatsService::cmd_remove_all_configs(int out) {
892 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800893 VLOG("StatsService::cmd_remove_all_configs was called");
894 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800895 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800896 return NO_ERROR;
897}
898
Yao Chena80e5c02018-09-04 13:55:29 -0700899status_t StatsService::cmd_dump_memory_info(int out) {
900 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800901 return NO_ERROR;
902}
903
Yao Chena80e5c02018-09-04 13:55:29 -0700904status_t StatsService::cmd_clear_puller_cache(int out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800905 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800906 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
907 ipc->getCallingPid(), ipc->getCallingUid());
Chenjie Yufa22d652018-02-05 14:37:48 -0800908 if (checkCallingPermission(String16(kPermissionDump))) {
Chenjie Yue2219202018-06-08 10:07:51 -0700909 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700910 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800911 return NO_ERROR;
912 } else {
913 return PERMISSION_DENIED;
914 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800915}
916
Yao Chena80e5c02018-09-04 13:55:29 -0700917status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Yao Chen876889c2018-05-02 11:16:16 -0700918 IPCThreadState* ipc = IPCThreadState::self();
919 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", ipc->getCallingPid(),
920 ipc->getCallingUid());
921 if (checkCallingPermission(String16(kPermissionDump))) {
922 bool enabled = true;
923 if (args.size() >= 2) {
924 enabled = atoi(args[1].c_str()) != 0;
925 }
926 mProcessor->setPrintLogs(enabled);
927 return NO_ERROR;
928 } else {
929 return PERMISSION_DENIED;
930 }
931}
932
Bookatzd2386572018-12-14 15:53:14 -0800933bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800934 return getUidFromString(args[uidArgIndex].c_str(), uid);
935}
936
937bool StatsService::getUidFromString(const char* s, int32_t& uid) {
Bookatzd2386572018-12-14 15:53:14 -0800938 if (*s == '\0') {
939 return false;
940 }
941 char* endc = NULL;
942 int64_t longUid = strtol(s, &endc, 0);
943 if (*endc != '\0') {
944 return false;
945 }
946 int32_t goodUid = static_cast<int32_t>(longUid);
947 if (longUid < 0 || static_cast<uint64_t>(longUid) != static_cast<uid_t>(goodUid)) {
948 return false; // It was not of uid_t type.
949 }
950 uid = goodUid;
951
952 int32_t callingUid = IPCThreadState::self()->getCallingUid();
953 return mEngBuild // UserDebug/EngBuild are allowed to impersonate uids.
954 || (callingUid == goodUid) // Anyone can 'impersonate' themselves.
955 || (callingUid == AID_ROOT && goodUid == AID_SHELL); // ROOT can impersonate SHELL.
956}
957
Max Dashouk11e0d402019-05-16 16:58:07 -0700958Status StatsService::informAllUidData(const ParcelFileDescriptor& fd) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600959 ENFORCE_UID(AID_SYSTEM);
Max Dashouk11e0d402019-05-16 16:58:07 -0700960 // Read stream into buffer.
961 string buffer;
962 if (!android::base::ReadFdToString(fd.get(), &buffer)) {
963 return exception(Status::EX_ILLEGAL_ARGUMENT, "Failed to read all data from the pipe.");
964 }
Jeff Sharkey6b649252018-04-16 09:50:22 -0600965
Max Dashouk11e0d402019-05-16 16:58:07 -0700966 // Parse buffer.
967 UidData uidData;
968 if (!uidData.ParseFromString(buffer)) {
969 return exception(Status::EX_ILLEGAL_ARGUMENT, "Error parsing proto stream for UidData.");
970 }
David Chende701692017-10-05 13:16:02 -0700971
Max Dashouk11e0d402019-05-16 16:58:07 -0700972 vector<String16> versionStrings;
973 vector<String16> installers;
974 vector<String16> packageNames;
975 vector<int32_t> uids;
976 vector<int64_t> versions;
977
978 const auto numEntries = uidData.app_info_size();
979 versionStrings.reserve(numEntries);
980 installers.reserve(numEntries);
981 packageNames.reserve(numEntries);
982 uids.reserve(numEntries);
983 versions.reserve(numEntries);
984
985 for (const auto& appInfo: uidData.app_info()) {
986 packageNames.emplace_back(String16(appInfo.package_name().c_str()));
987 uids.push_back(appInfo.uid());
988 versions.push_back(appInfo.version());
989 versionStrings.emplace_back(String16(appInfo.version_string().c_str()));
990 installers.emplace_back(String16(appInfo.installer().c_str()));
991 }
992
993 mUidMap->updateMap(getElapsedRealtimeNs(),
994 uids,
995 versions,
996 versionStrings,
997 packageNames,
998 installers);
999
1000 VLOG("StatsService::informAllUidData UidData proto parsed successfully.");
David Chende701692017-10-05 13:16:02 -07001001 return Status::ok();
1002}
1003
dwchen730403e2018-10-29 11:41:56 -07001004Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version,
1005 const String16& version_string, const String16& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001006 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -07001007
Jeff Sharkey6b649252018-04-16 09:50:22 -06001008 VLOG("StatsService::informOnePackage was called");
dwchen730403e2018-10-29 11:41:56 -07001009 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version, version_string, installer);
David Chende701692017-10-05 13:16:02 -07001010 return Status::ok();
1011}
1012
1013Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001014 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -07001015
Jeff Sharkey6b649252018-04-16 09:50:22 -06001016 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -07001017 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -08001018 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -07001019 return Status::ok();
1020}
1021
Yao Chenef99c4f2017-09-22 16:26:54 -07001022Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001023 ENFORCE_UID(AID_SYSTEM);
1024
yro74fed972017-11-27 14:42:42 -08001025 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -07001026 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -08001027 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
1028 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
1029 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -08001030 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -08001031 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -08001032 } else {
1033 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
1034 }
Bookatz1b0b1142017-09-08 11:58:42 -07001035 return Status::ok();
1036}
1037
Yangster-mac932ecec2018-02-01 10:23:52 -08001038Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001039 ENFORCE_UID(AID_SYSTEM);
1040
Yangster-mac932ecec2018-02-01 10:23:52 -08001041 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -07001042 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -08001043 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
1044 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
1045 if (alarmSet.size() > 0) {
1046 VLOG("Found periodic alarm fired.");
1047 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
1048 } else {
1049 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
1050 }
1051 return Status::ok();
1052}
1053
Yao Chenef99c4f2017-09-22 16:26:54 -07001054Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001055 ENFORCE_UID(AID_SYSTEM);
1056
yro74fed972017-11-27 14:42:42 -08001057 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -07001058 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -08001059 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -07001060 return Status::ok();
1061}
1062
Yao Chenef99c4f2017-09-22 16:26:54 -07001063Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001064 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001065
1066 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -08001067 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -07001068 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001069 return Status::ok();
1070}
1071
Yangster-mac892f3d32018-05-02 14:16:48 -07001072Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001073 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -07001074 VLOG("StatsService::informDeviceShutdown");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001075 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001076 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
yro947fbce2017-11-15 22:50:23 -08001077 return Status::ok();
1078}
1079
Yao Chenef99c4f2017-09-22 16:26:54 -07001080void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -07001081 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1082 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -08001083 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -07001084 statsCompanion->statsdReady();
1085 } else {
yro74fed972017-11-27 14:42:42 -08001086 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -07001087 }
1088}
1089
Yao Chenef99c4f2017-09-22 16:26:54 -07001090Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001091 ENFORCE_UID(AID_SYSTEM);
1092
yro74fed972017-11-27 14:42:42 -08001093 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -07001094 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1095 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -07001096 return Status::fromExceptionCode(
1097 Status::EX_NULL_POINTER,
1098 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -07001099 }
yro74fed972017-11-27 14:42:42 -08001100 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001101 IInterface::asBinder(statsCompanion)->linkToDeath(this);
Chenjie Yue2219202018-06-08 10:07:51 -07001102 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -08001103 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
1104 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -08001105 SubscriberReporter::getInstance().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
Jeff Sharkey6b649252018-04-16 09:50:22 -06001130Status StatsService::getData(int64_t key, const String16& packageName, vector<uint8_t>* output) {
1131 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1132
David Chenadaf8b32017-11-03 15:42:08 -07001133 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -08001134 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001135 ConfigKey configKey(ipc->getCallingUid(), key);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001136 // The dump latency does not matter here since we do not include the current bucket, we do not
1137 // need to pull any new data anyhow.
David Chen56ae0d92018-05-11 16:00:22 -07001138 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001139 true /* erase_data */, GET_DATA_CALLED, FAST, output);
Bookatz4f716292018-04-10 17:15:12 -07001140 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001141}
1142
Jeff Sharkey6b649252018-04-16 09:50:22 -06001143Status StatsService::getMetadata(const String16& packageName, vector<uint8_t>* output) {
1144 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1145
David Chen2e8f3802017-11-22 10:56:48 -08001146 IPCThreadState* ipc = IPCThreadState::self();
1147 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
1148 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001149 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
1150 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -08001151}
1152
Jeff Sharkey6b649252018-04-16 09:50:22 -06001153Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
1154 const String16& packageName) {
1155 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1156
David Chenadaf8b32017-11-03 15:42:08 -07001157 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -07001158 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -08001159 return Status::ok();
1160 } else {
Bookatz4f716292018-04-10 17:15:12 -07001161 ALOGE("Could not parse malformatted StatsdConfig");
1162 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
1163 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -08001164 }
1165}
1166
David Chen9fdd4032018-03-20 14:38:56 -07001167bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
1168 ConfigKey configKey(uid, key);
1169 StatsdConfig cfg;
1170 if (config.size() > 0) { // If the config is empty, skip parsing.
1171 if (!cfg.ParseFromArray(&config[0], config.size())) {
1172 return false;
1173 }
1174 }
1175 mConfigManager->UpdateConfig(configKey, cfg);
1176 return true;
1177}
1178
Jeff Sharkey6b649252018-04-16 09:50:22 -06001179Status StatsService::removeDataFetchOperation(int64_t key, const String16& packageName) {
1180 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1181
Bookatz4f716292018-04-10 17:15:12 -07001182 IPCThreadState* ipc = IPCThreadState::self();
1183 ConfigKey configKey(ipc->getCallingUid(), key);
1184 mConfigManager->RemoveConfigReceiver(configKey);
1185 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -08001186}
1187
Jeff Sharkey6b649252018-04-16 09:50:22 -06001188Status StatsService::setDataFetchOperation(int64_t key,
1189 const sp<android::IBinder>& intentSender,
1190 const String16& packageName) {
1191 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1192
Bookatz4f716292018-04-10 17:15:12 -07001193 IPCThreadState* ipc = IPCThreadState::self();
1194 ConfigKey configKey(ipc->getCallingUid(), key);
1195 mConfigManager->SetConfigReceiver(configKey, intentSender);
David Chen48944902018-05-03 10:29:11 -07001196 if (StorageManager::hasConfigMetricsReport(configKey)) {
1197 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
1198 configKey.ToString().c_str());
1199 mProcessor->noteOnDiskData(configKey);
1200 }
Bookatz4f716292018-04-10 17:15:12 -07001201 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001202}
1203
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001204Status StatsService::setActiveConfigsChangedOperation(const sp<android::IBinder>& intentSender,
1205 const String16& packageName,
1206 vector<int64_t>* output) {
1207 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1208
1209 IPCThreadState* ipc = IPCThreadState::self();
Tej Singh6ede28b2019-01-29 17:06:54 -08001210 int uid = ipc->getCallingUid();
1211 mConfigManager->SetActiveConfigsChangedReceiver(uid, intentSender);
1212 if (output != nullptr) {
1213 mProcessor->GetActiveConfigs(uid, *output);
1214 } else {
1215 ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
1216 }
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001217 return Status::ok();
1218}
1219
1220Status StatsService::removeActiveConfigsChangedOperation(const String16& packageName) {
1221 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1222
1223 IPCThreadState* ipc = IPCThreadState::self();
1224 mConfigManager->RemoveActiveConfigsChangedReceiver(ipc->getCallingUid());
1225 return Status::ok();
1226}
1227
Jeff Sharkey6b649252018-04-16 09:50:22 -06001228Status StatsService::removeConfiguration(int64_t key, const String16& packageName) {
1229 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1230
Bookatz4f716292018-04-10 17:15:12 -07001231 IPCThreadState* ipc = IPCThreadState::self();
1232 ConfigKey configKey(ipc->getCallingUid(), key);
1233 mConfigManager->RemoveConfig(configKey);
1234 SubscriberReporter::getInstance().removeConfig(configKey);
1235 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001236}
1237
Bookatzc6977972018-01-16 16:55:05 -08001238Status StatsService::setBroadcastSubscriber(int64_t configId,
1239 int64_t subscriberId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001240 const sp<android::IBinder>& intentSender,
1241 const String16& packageName) {
1242 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1243
Bookatzc6977972018-01-16 16:55:05 -08001244 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001245 IPCThreadState* ipc = IPCThreadState::self();
1246 ConfigKey configKey(ipc->getCallingUid(), configId);
1247 SubscriberReporter::getInstance()
1248 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
1249 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001250}
1251
1252Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001253 int64_t subscriberId,
1254 const String16& packageName) {
1255 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1256
Bookatzc6977972018-01-16 16:55:05 -08001257 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001258 IPCThreadState* ipc = IPCThreadState::self();
1259 ConfigKey configKey(ipc->getCallingUid(), configId);
1260 SubscriberReporter::getInstance()
1261 .unsetBroadcastSubscriber(configKey, subscriberId);
1262 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001263}
1264
yrobe6d7f92018-05-04 13:02:53 -07001265Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
1266 // Permission check not necessary as it's meant for applications to write to
1267 // statsd.
1268 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
1269 IPCThreadState::self()->getCallingUid(), label,
1270 state);
1271 return Status::ok();
1272}
1273
Tej Singha0c89dd2019-01-25 16:39:18 -08001274Status StatsService::registerPullerCallback(int32_t atomTag,
1275 const sp<android::os::IStatsPullerCallback>& pullerCallback,
1276 const String16& packageName) {
1277 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1278
1279 VLOG("StatsService::registerPullerCallback called.");
1280 mPullerManager->RegisterPullerCallback(atomTag, pullerCallback);
1281 return Status::ok();
1282}
1283
1284Status StatsService::unregisterPullerCallback(int32_t atomTag, const String16& packageName) {
1285 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1286
1287 VLOG("StatsService::unregisterPullerCallback called.");
1288 mPullerManager->UnregisterPullerCallback(atomTag);
1289 return Status::ok();
1290}
1291
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001292Status StatsService::sendBinaryPushStateChangedAtom(const android::String16& trainNameIn,
1293 const int64_t trainVersionCodeIn,
1294 const int options,
1295 const int32_t state,
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001296 const std::vector<int64_t>& experimentIdsIn) {
Tej Singh53f9dee2019-04-30 17:45:54 -07001297 // Note: We skip the usage stats op check here since we do not have a package name.
1298 // This is ok since we are overloading the usage_stats permission.
1299 // This method only sends data, it does not receive it.
1300 pid_t pid = IPCThreadState::self()->getCallingPid();
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001301 uid_t uid = IPCThreadState::self()->getCallingUid();
Tej Singh73f8e9b2019-05-19 16:52:38 -07001302 // Root, system, and shell always have access
Tej Singh53f9dee2019-04-30 17:45:54 -07001303 if (uid != AID_ROOT && uid != AID_SYSTEM && uid != AID_SHELL) {
1304 // Caller must be granted these permissions
1305 if (!checkCallingPermission(String16(kPermissionDump))) {
1306 return exception(binder::Status::EX_SECURITY,
1307 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1308 kPermissionDump));
1309 }
1310 if (!checkCallingPermission(String16(kPermissionUsage))) {
1311 return exception(binder::Status::EX_SECURITY,
1312 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1313 kPermissionUsage));
1314 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001315 }
1316
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001317 bool readTrainInfoSuccess = false;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001318 InstallTrainInfo trainInfoOnDisk;
1319 readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfoOnDisk);
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001320
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001321 bool resetExperimentIds = false;
1322 int64_t trainVersionCode = trainVersionCodeIn;
1323 std::string trainNameUtf8 = std::string(String8(trainNameIn).string());
1324 if (readTrainInfoSuccess) {
1325 // Keep the old train version if we received an empty version.
1326 if (trainVersionCodeIn == -1) {
1327 trainVersionCode = trainInfoOnDisk.trainVersionCode;
1328 } else if (trainVersionCodeIn != trainInfoOnDisk.trainVersionCode) {
1329 // Reset experiment ids if we receive a new non-empty train version.
1330 resetExperimentIds = true;
1331 }
1332
1333 // Keep the old train name if we received an empty train name.
1334 if (trainNameUtf8.size() == 0) {
1335 trainNameUtf8 = trainInfoOnDisk.trainName;
1336 } else if (trainNameUtf8 != trainInfoOnDisk.trainName) {
1337 // Reset experiment ids if we received a new valid train name.
1338 resetExperimentIds = true;
1339 }
1340
1341 // Reset if we received a different experiment id.
1342 if (!experimentIdsIn.empty() &&
1343 (trainInfoOnDisk.experimentIds.empty() ||
1344 experimentIdsIn[0] != trainInfoOnDisk.experimentIds[0])) {
1345 resetExperimentIds = true;
1346 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001347 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001348
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001349 // Find the right experiment IDs
1350 std::vector<int64_t> experimentIds;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001351 if (resetExperimentIds || !readTrainInfoSuccess) {
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001352 experimentIds = experimentIdsIn;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001353 } else {
1354 experimentIds = trainInfoOnDisk.experimentIds;
1355 }
1356
1357 if (!experimentIds.empty()) {
1358 int64_t firstId = experimentIds[0];
1359 switch (state) {
1360 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALL_SUCCESS:
1361 experimentIds.push_back(firstId + 1);
1362 break;
1363 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_INITIATED:
1364 experimentIds.push_back(firstId + 2);
1365 break;
1366 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_SUCCESS:
1367 experimentIds.push_back(firstId + 3);
1368 break;
1369 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001370 }
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001371
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001372 // Flatten the experiment IDs to proto
1373 vector<uint8_t> experimentIdsProtoBuffer;
1374 writeExperimentIdsToProto(experimentIds, &experimentIdsProtoBuffer);
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001375 StorageManager::writeTrainInfo(trainVersionCode, trainNameUtf8, state, experimentIds);
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001376
1377 userid_t userId = multiuser_get_user_id(uid);
1378 bool requiresStaging = options & IStatsManager::FLAG_REQUIRE_STAGING;
1379 bool rollbackEnabled = options & IStatsManager::FLAG_ROLLBACK_ENABLED;
1380 bool requiresLowLatencyMonitor = options & IStatsManager::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001381 LogEvent event(trainNameUtf8, trainVersionCode, requiresStaging, rollbackEnabled,
1382 requiresLowLatencyMonitor, state, experimentIdsProtoBuffer, userId);
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001383 mProcessor->OnLogEvent(&event);
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001384 return Status::ok();
1385}
1386
Tej Singh73f8e9b2019-05-19 16:52:38 -07001387Status StatsService::sendWatchdogRollbackOccurredAtom(const int32_t rollbackTypeIn,
1388 const android::String16& packageNameIn,
1389 const int64_t packageVersionCodeIn) {
1390 // Note: We skip the usage stats op check here since we do not have a package name.
1391 // This is ok since we are overloading the usage_stats permission.
1392 // This method only sends data, it does not receive it.
1393 pid_t pid = IPCThreadState::self()->getCallingPid();
1394 uid_t uid = IPCThreadState::self()->getCallingUid();
1395 // Root, system, and shell always have access
1396 if (uid != AID_ROOT && uid != AID_SYSTEM && uid != AID_SHELL) {
1397 // Caller must be granted these permissions
1398 if (!checkCallingPermission(String16(kPermissionDump))) {
1399 return exception(binder::Status::EX_SECURITY,
1400 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1401 kPermissionDump));
1402 }
1403 if (!checkCallingPermission(String16(kPermissionUsage))) {
1404 return exception(binder::Status::EX_SECURITY,
1405 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1406 kPermissionUsage));
1407 }
1408 }
1409
1410 android::util::stats_write(android::util::WATCHDOG_ROLLBACK_OCCURRED,
1411 rollbackTypeIn, String8(packageNameIn).string(), packageVersionCodeIn);
1412
1413 // Fast return to save disk read.
1414 if (rollbackTypeIn != android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS
1415 && rollbackTypeIn !=
1416 android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE) {
1417 return Status::ok();
1418 }
1419
1420 bool readTrainInfoSuccess = false;
1421 InstallTrainInfo trainInfoOnDisk;
1422 readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfoOnDisk);
1423
1424 if (!readTrainInfoSuccess) {
1425 return Status::ok();
1426 }
1427 std::vector<int64_t> experimentIds = trainInfoOnDisk.experimentIds;
1428 if (experimentIds.empty()) {
1429 return Status::ok();
1430 }
1431 switch (rollbackTypeIn) {
1432 case android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE:
1433 experimentIds.push_back(experimentIds[0] + 4);
1434 break;
1435 case android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS:
1436 experimentIds.push_back(experimentIds[0] + 5);
1437 break;
1438 }
1439 StorageManager::writeTrainInfo(trainInfoOnDisk.trainVersionCode, trainInfoOnDisk.trainName,
1440 trainInfoOnDisk.status, experimentIds);
1441 return Status::ok();
1442}
1443
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001444Status StatsService::getRegisteredExperimentIds(std::vector<int64_t>* experimentIdsOut) {
1445 uid_t uid = IPCThreadState::self()->getCallingUid();
1446
1447 // Caller must be granted these permissions
1448 if (!checkCallingPermission(String16(kPermissionDump))) {
1449 return exception(binder::Status::EX_SECURITY,
1450 StringPrintf("UID %d lacks permission %s", uid, kPermissionDump));
1451 }
1452 if (!checkCallingPermission(String16(kPermissionUsage))) {
1453 return exception(binder::Status::EX_SECURITY,
1454 StringPrintf("UID %d lacks permission %s", uid, kPermissionUsage));
1455 }
1456 // TODO: add verifier permission
1457
1458 // Read the latest train info
1459 InstallTrainInfo trainInfo;
1460 if (!StorageManager::readTrainInfo(trainInfo)) {
1461 // No train info means no experiment IDs, return an empty list
1462 experimentIdsOut->clear();
1463 return Status::ok();
1464 }
1465
1466 // Copy the experiment IDs to the out vector
1467 experimentIdsOut->assign(trainInfo.experimentIds.begin(), trainInfo.experimentIds.end());
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001468 return Status::ok();
1469}
1470
David Chen1d7b0cd2017-11-15 14:20:04 -08001471void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001472 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001473 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1474 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001475 ALOGW("Reset statsd upon system server restarts.");
Tej Singhf53d4452019-05-09 18:17:59 -07001476 int64_t systemServerRestartNs = getElapsedRealtimeNs();
1477 ProtoOutputStream proto;
1478 mProcessor->WriteActiveConfigsToProtoOutputStream(systemServerRestartNs,
1479 STATSCOMPANION_DIED, &proto);
1480
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001481 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED, FAST);
Yangster-mac892f3d32018-05-02 14:16:48 -07001482 mProcessor->resetConfigs();
Tej Singhf53d4452019-05-09 18:17:59 -07001483
1484 std::string serializedActiveConfigs;
1485 if (proto.serializeToString(&serializedActiveConfigs)) {
1486 ActiveConfigList activeConfigs;
1487 if (activeConfigs.ParseFromString(serializedActiveConfigs)) {
1488 mProcessor->SetConfigsActiveState(activeConfigs, systemServerRestartNs);
1489 }
1490 }
Yangster-mac892f3d32018-05-02 14:16:48 -07001491 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001492 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1493 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
1494 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001495 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001496}
1497
Yao Chenef99c4f2017-09-22 16:26:54 -07001498} // namespace statsd
1499} // namespace os
1500} // namespace android