blob: d5e331495164b73fa3659a0323e5dcf9b74c25b7 [file] [log] [blame]
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001/*
yro0feae942017-11-15 14:38:48 -08002 * Copyright (C) 2017 The Android Open Source Project
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Tej Singh484524a2018-02-01 15:10:05 -080017#define DEBUG false // STOPSHIP if true
Joe Onorato9fc9edf2017-10-15 20:08:52 -070018#include "Log.h"
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070019
20#include "StatsService.h"
Yangster-mac330af582018-02-08 15:24:38 -080021#include "stats_log_util.h"
Yao Chen8d9989b2017-11-18 18:54:50 -080022#include "android-base/stringprintf.h"
David Chenadaf8b32017-11-03 15:42:08 -070023#include "config/ConfigKey.h"
24#include "config/ConfigManager.h"
Yao Chenb3561512017-11-21 18:07:17 -080025#include "guardrail/StatsdStats.h"
yro947fbce2017-11-15 22:50:23 -080026#include "storage/StorageManager.h"
Bookatzc6977972018-01-16 16:55:05 -080027#include "subscriber/SubscriberReporter.h"
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070028
David Chen0656b7a2017-09-13 15:53:39 -070029#include <android-base/file.h>
Tej Singh53f9dee2019-04-30 17:45:54 -070030#include <android-base/strings.h>
Chenjie Yu6b1667c2019-01-18 10:09:33 -080031#include <cutils/multiuser.h>
David Chen0656b7a2017-09-13 15:53:39 -070032#include <frameworks/base/cmds/statsd/src/statsd_config.pb.h>
Max Dashouk11e0d402019-05-16 16:58:07 -070033#include <frameworks/base/cmds/statsd/src/uid_data.pb.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070034#include <private/android_filesystem_config.h>
Jeffrey Huang74fc4352020-03-06 15:18:33 -080035#include <statslog_statsd.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070036#include <stdio.h>
Yao Chen482d2722017-09-12 13:25:43 -070037#include <stdlib.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070038#include <sys/system_properties.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070039#include <unistd.h>
Yao Chena80e5c02018-09-04 13:55:29 -070040#include <utils/String16.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070041
42using namespace android;
43
Jeff Sharkey6b649252018-04-16 09:50:22 -060044using android::base::StringPrintf;
Bookatzff71cad2018-09-20 17:17:49 -070045using android::util::FIELD_COUNT_REPEATED;
46using android::util::FIELD_TYPE_MESSAGE;
Jeff Sharkey6b649252018-04-16 09:50:22 -060047
Ruchir Rastogie449b0c2020-02-10 17:40:09 -080048using Status = ::ndk::ScopedAStatus;
49
Bookatz906a35c2017-09-20 15:26:44 -070050namespace android {
51namespace os {
52namespace statsd {
53
David Chenadaf8b32017-11-03 15:42:08 -070054constexpr const char* kPermissionDump = "android.permission.DUMP";
Jeff Sharkey6b649252018-04-16 09:50:22 -060055
Tej Singh10458ec2020-03-17 11:04:02 -070056constexpr const char* kPermissionRegisterPullAtom = "android.permission.REGISTER_STATS_PULL_ATOM";
57
yro03faf092017-12-12 00:17:50 -080058#define STATS_SERVICE_DIR "/data/misc/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070059
Bookatzff71cad2018-09-20 17:17:49 -070060// for StatsDataDumpProto
61const int FIELD_ID_REPORTS_LIST = 1;
62
Ruchir Rastogie449b0c2020-02-10 17:40:09 -080063static Status exception(int32_t code, const std::string& msg) {
Jeff Sharkey6b649252018-04-16 09:50:22 -060064 ALOGE("%s (%d)", msg.c_str(), code);
Tej Singh10458ec2020-03-17 11:04:02 -070065 return Status::fromExceptionCodeWithMessage(code, msg.c_str());
Jeff Sharkey6b649252018-04-16 09:50:22 -060066}
67
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -080068static bool checkPermission(const char* permission) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -080069 pid_t pid = AIBinder_getCallingPid();
70 uid_t uid = AIBinder_getCallingUid();
Jonathan Nguyena0e6de12020-01-28 18:33:55 -080071 return checkPermissionForIds(permission, pid, uid);
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -080072}
73
Ruchir Rastogie449b0c2020-02-10 17:40:09 -080074Status checkUid(uid_t expectedUid) {
75 uid_t uid = AIBinder_getCallingUid();
Jeff Sharkey6b649252018-04-16 09:50:22 -060076 if (uid == expectedUid || uid == AID_ROOT) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -080077 return Status::ok();
Jeff Sharkey6b649252018-04-16 09:50:22 -060078 } else {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -080079 return exception(EX_SECURITY,
80 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
Jeff Sharkey6b649252018-04-16 09:50:22 -060081 }
82}
83
84#define ENFORCE_UID(uid) { \
Ruchir Rastogie449b0c2020-02-10 17:40:09 -080085 Status status = checkUid((uid)); \
Jeff Sharkey6b649252018-04-16 09:50:22 -060086 if (!status.isOk()) { \
87 return status; \
88 } \
89}
90
Yao Chen0f861862019-03-27 11:51:15 -070091StatsService::StatsService(const sp<Looper>& handlerLooper, shared_ptr<LogEventQueue> queue)
92 : mAnomalyAlarmMonitor(new AlarmMonitor(
93 MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
Ruchir Rastogie449b0c2020-02-10 17:40:09 -080094 [](const shared_ptr<IStatsCompanionService>& sc, int64_t timeMillis) {
Yao Chen0f861862019-03-27 11:51:15 -070095 if (sc != nullptr) {
96 sc->setAnomalyAlarm(timeMillis);
97 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
98 }
99 },
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800100 [](const shared_ptr<IStatsCompanionService>& sc) {
Yao Chen0f861862019-03-27 11:51:15 -0700101 if (sc != nullptr) {
102 sc->cancelAnomalyAlarm();
103 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
104 }
105 })),
106 mPeriodicAlarmMonitor(new AlarmMonitor(
107 MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800108 [](const shared_ptr<IStatsCompanionService>& sc, int64_t timeMillis) {
Yao Chen0f861862019-03-27 11:51:15 -0700109 if (sc != nullptr) {
110 sc->setAlarmForSubscriberTriggering(timeMillis);
111 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
112 }
113 },
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800114 [](const shared_ptr<IStatsCompanionService>& sc) {
Yao Chen0f861862019-03-27 11:51:15 -0700115 if (sc != nullptr) {
116 sc->cancelAlarmForSubscriberTriggering();
117 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
118 }
119 })),
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800120 mEventQueue(queue),
Tej Singhe678cb72020-04-14 16:23:30 -0700121 mBootCompleteTrigger({kBootCompleteTag, kUidMapReceivedTag, kAllPullersRegisteredTag},
122 [this]() { mProcessor->onStatsdInitCompleted(getElapsedRealtimeNs()); }),
Tej Singh769f35f2020-04-11 03:39:12 -0700123 mStatsCompanionServiceDeathRecipient(
124 AIBinder_DeathRecipient_new(StatsService::statsCompanionServiceDied)) {
Yao Chen4ce07292019-02-13 13:06:36 -0800125 mUidMap = UidMap::getInstance();
Chenjie Yue2219202018-06-08 10:07:51 -0700126 mPullerManager = new StatsPullerManager();
Chenjie Yu80f91122018-01-31 20:24:50 -0800127 StatsPuller::SetUidMap(mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700128 mConfigManager = new ConfigManager();
Chenjie Yue2219202018-06-08 10:07:51 -0700129 mProcessor = new StatsLogProcessor(
130 mUidMap, mPullerManager, mAnomalyAlarmMonitor, mPeriodicAlarmMonitor,
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800131 getElapsedRealtimeNs(),
132 [this](const ConfigKey& key) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800133 shared_ptr<IPendingIntentRef> receiver = mConfigManager->GetConfigReceiver(key);
Jeffrey Huangad213742019-12-16 13:50:06 -0800134 if (receiver == nullptr) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800135 VLOG("Could not find a broadcast receiver for %s", key.ToString().c_str());
Chenjie Yue2219202018-06-08 10:07:51 -0700136 return false;
Jeffrey Huangad213742019-12-16 13:50:06 -0800137 } else if (receiver->sendDataBroadcast(
138 mProcessor->getLastReportTimeNs(key)).isOk()) {
Chenjie Yue2219202018-06-08 10:07:51 -0700139 return true;
Jeffrey Huangad213742019-12-16 13:50:06 -0800140 } else {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800141 VLOG("Failed to send a broadcast for receiver %s", key.ToString().c_str());
Jeffrey Huangad213742019-12-16 13:50:06 -0800142 return false;
Chenjie Yue2219202018-06-08 10:07:51 -0700143 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800144 },
145 [this](const int& uid, const vector<int64_t>& activeConfigs) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800146 shared_ptr<IPendingIntentRef> receiver =
Jeffrey Huang47537a12020-01-06 15:35:34 -0800147 mConfigManager->GetActiveConfigsChangedReceiver(uid);
148 if (receiver == nullptr) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800149 VLOG("Could not find receiver for uid %d", uid);
150 return false;
Jeffrey Huang47537a12020-01-06 15:35:34 -0800151 } else if (receiver->sendActiveConfigsChangedBroadcast(activeConfigs).isOk()) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800152 VLOG("StatsService::active configs broadcast succeeded for uid %d" , uid);
153 return true;
Jeffrey Huang47537a12020-01-06 15:35:34 -0800154 } else {
155 VLOG("StatsService::active configs broadcast failed for uid %d" , uid);
156 return false;
Tej Singh6ede28b2019-01-29 17:06:54 -0800157 }
Chenjie Yue2219202018-06-08 10:07:51 -0700158 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700159
Tej Singh9ec159a2019-11-14 11:59:48 -0800160 mUidMap->setListener(mProcessor);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700161 mConfigManager->AddListener(mProcessor);
162
163 init_system_properties();
Yao Chen0f861862019-03-27 11:51:15 -0700164
165 if (mEventQueue != nullptr) {
166 std::thread pushedEventThread([this] { readLogs(); });
167 pushedEventThread.detach();
168 }
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700169}
170
Yao Chenef99c4f2017-09-22 16:26:54 -0700171StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700172}
173
Yao Chen0f861862019-03-27 11:51:15 -0700174/* Runs on a dedicated thread to process pushed events. */
175void StatsService::readLogs() {
176 // Read forever..... long live statsd
177 while (1) {
178 // Block until an event is available.
179 auto event = mEventQueue->waitPop();
180 // Pass it to StatsLogProcess to all configs/metrics
181 // At this point, the LogEventQueue is not blocked, so that the socketListener
182 // can read events from the socket and write to buffer to avoid data drop.
183 mProcessor->OnLogEvent(event.get());
184 // The ShellSubscriber is only used by shell for local debugging.
185 if (mShellSubscriber != nullptr) {
186 mShellSubscriber->onLogEvent(*event);
187 }
188 }
189}
190
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700191void StatsService::init_system_properties() {
192 mEngBuild = false;
193 const prop_info* buildType = __system_property_find("ro.build.type");
194 if (buildType != NULL) {
195 __system_property_read_callback(buildType, init_build_type_callback, this);
196 }
David Chen0656b7a2017-09-13 15:53:39 -0700197}
198
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700199void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
200 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700201 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700202 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
203 }
204}
205
206/**
Bookatzff71cad2018-09-20 17:17:49 -0700207 * Write data from statsd.
208 * Format for statsdStats: adb shell dumpsys stats --metadata [-v] [--proto]
209 * Format for data report: adb shell dumpsys stats [anything other than --metadata] [--proto]
210 * Anything ending in --proto will be in proto format.
211 * Anything without --metadata as the first argument will be report information.
212 * (bugreports call "adb shell dumpsys stats --dump-priority NORMAL -a --proto")
213 * TODO: Come up with a more robust method of enacting <serviceutils/PriorityDumper.h>.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700214 */
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800215status_t StatsService::dump(int fd, const char** args, uint32_t numArgs) {
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -0800216 if (!checkPermission(kPermissionDump)) {
Tej Singhdd83d702018-04-10 17:24:50 -0700217 return PERMISSION_DENIED;
218 }
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800219
220 int lastArg = numArgs - 1;
Bookatzff71cad2018-09-20 17:17:49 -0700221 bool asProto = false;
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800222 if (lastArg >= 0 && string(args[lastArg]) == "--proto") { // last argument
Bookatzff71cad2018-09-20 17:17:49 -0700223 asProto = true;
224 lastArg--;
Yao Chen884c8c12018-01-26 10:36:25 -0800225 }
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800226 if (numArgs > 0 && string(args[0]) == "--metadata") { // first argument
Bookatzff71cad2018-09-20 17:17:49 -0700227 // Request is to dump statsd stats.
228 bool verbose = false;
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800229 if (lastArg >= 0 && string(args[lastArg]) == "-v") {
Bookatzff71cad2018-09-20 17:17:49 -0700230 verbose = true;
231 lastArg--;
232 }
233 dumpStatsdStats(fd, verbose, asProto);
234 } else {
235 // Request is to dump statsd report data.
236 if (asProto) {
237 dumpIncidentSection(fd);
238 } else {
239 dprintf(fd, "Non-proto format of stats data dump not available; see proto version.\n");
240 }
Tej Singh41b3f9a2018-04-03 17:06:35 -0700241 }
Yao Chen884c8c12018-01-26 10:36:25 -0800242
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700243 return NO_ERROR;
244}
245
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700246/**
Tej Singh41b3f9a2018-04-03 17:06:35 -0700247 * Write debugging data about statsd in text or proto format.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700248 */
Bookatzff71cad2018-09-20 17:17:49 -0700249void StatsService::dumpStatsdStats(int out, bool verbose, bool proto) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700250 if (proto) {
251 vector<uint8_t> data;
252 StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
253 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700254 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700255 }
256 } else {
257 StatsdStats::getInstance().dumpStats(out);
258 mProcessor->dumpStates(out, verbose);
259 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700260}
261
262/**
Bookatzff71cad2018-09-20 17:17:49 -0700263 * Write stats report data in StatsDataDumpProto incident section format.
264 */
265void StatsService::dumpIncidentSection(int out) {
266 ProtoOutputStream proto;
267 for (const ConfigKey& configKey : mConfigManager->GetAllConfigKeys()) {
268 uint64_t reportsListToken =
269 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS_LIST);
Tej Singh61f869e2020-06-12 17:25:17 -0700270 // Don't include the current bucket to avoid skipping buckets.
271 // If we need to include the current bucket later, consider changing to NO_TIME_CONSTRAINTS
272 // or other alternatives to avoid skipping buckets for pulled metrics.
Bookatzff71cad2018-09-20 17:17:49 -0700273 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
Tej Singh61f869e2020-06-12 17:25:17 -0700274 false /* includeCurrentBucket */, false /* erase_data */,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000275 ADB_DUMP,
276 FAST,
277 &proto);
Bookatzff71cad2018-09-20 17:17:49 -0700278 proto.end(reportsListToken);
279 proto.flush(out);
Bookatzc71d9012018-12-19 12:28:38 -0800280 proto.clear();
Bookatzff71cad2018-09-20 17:17:49 -0700281 }
282}
283
284/**
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700285 * Implementation of the adb shell cmd stats command.
286 */
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800287status_t StatsService::handleShellCommand(int in, int out, int err, const char** argv,
288 uint32_t argc) {
289 uid_t uid = AIBinder_getCallingUid();
Stanislav Zholnind7674c22020-02-17 17:48:12 +0000290 if (uid != AID_ROOT && uid != AID_SHELL) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600291 return PERMISSION_DENIED;
292 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700293
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800294 Vector<String8> utf8Args;
295 utf8Args.setCapacity(argc);
296 for (uint32_t i = 0; i < argc; i++) {
297 utf8Args.push(String8(argv[i]));
298 }
299
300 if (argc >= 1) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700301 // adb shell cmd stats config ...
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800302 if (!utf8Args[0].compare(String8("config"))) {
303 return cmd_config(in, out, err, utf8Args);
David Chen0656b7a2017-09-13 15:53:39 -0700304 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700305
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800306 if (!utf8Args[0].compare(String8("print-uid-map"))) {
307 return cmd_print_uid_map(out, utf8Args);
David Chende701692017-10-05 13:16:02 -0700308 }
Yao Chen729093d2017-10-16 10:33:26 -0700309
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800310 if (!utf8Args[0].compare(String8("dump-report"))) {
311 return cmd_dump_report(out, utf8Args);
Yao Chen729093d2017-10-16 10:33:26 -0700312 }
David Chen1481fe12017-10-16 13:16:34 -0700313
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800314 if (!utf8Args[0].compare(String8("pull-source")) && argc > 1) {
315 return cmd_print_pulled_metrics(out, utf8Args);
David Chen1481fe12017-10-16 13:16:34 -0700316 }
David Chenadaf8b32017-11-03 15:42:08 -0700317
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800318 if (!utf8Args[0].compare(String8("send-broadcast"))) {
319 return cmd_trigger_broadcast(out, utf8Args);
David Chen1d7b0cd2017-11-15 14:20:04 -0800320 }
321
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800322 if (!utf8Args[0].compare(String8("print-stats"))) {
323 return cmd_print_stats(out, utf8Args);
David Chenadaf8b32017-11-03 15:42:08 -0700324 }
yro87d983c2017-11-14 21:31:43 -0800325
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800326 if (!utf8Args[0].compare(String8("meminfo"))) {
Yao Chen8d9989b2017-11-18 18:54:50 -0800327 return cmd_dump_memory_info(out);
328 }
yro947fbce2017-11-15 22:50:23 -0800329
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800330 if (!utf8Args[0].compare(String8("write-to-disk"))) {
yro947fbce2017-11-15 22:50:23 -0800331 return cmd_write_data_to_disk(out);
332 }
Bookatzb223c4e2018-02-01 15:35:04 -0800333
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800334 if (!utf8Args[0].compare(String8("log-app-breadcrumb"))) {
335 return cmd_log_app_breadcrumb(out, utf8Args);
Bookatzb223c4e2018-02-01 15:35:04 -0800336 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800337
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800338 if (!utf8Args[0].compare(String8("log-binary-push"))) {
339 return cmd_log_binary_push(out, utf8Args);
Tej Singh53f9dee2019-04-30 17:45:54 -0700340 }
341
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800342 if (!utf8Args[0].compare(String8("clear-puller-cache"))) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800343 return cmd_clear_puller_cache(out);
344 }
Yao Chen876889c2018-05-02 11:16:16 -0700345
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800346 if (!utf8Args[0].compare(String8("print-logs"))) {
347 return cmd_print_logs(out, utf8Args);
Yao Chen876889c2018-05-02 11:16:16 -0700348 }
Ruchir Rastogie92edba2020-04-22 15:37:32 -0700349
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800350 if (!utf8Args[0].compare(String8("send-active-configs"))) {
351 return cmd_trigger_active_config_broadcast(out, utf8Args);
Tej Singh6ede28b2019-01-29 17:06:54 -0800352 }
Ruchir Rastogie92edba2020-04-22 15:37:32 -0700353
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800354 if (!utf8Args[0].compare(String8("data-subscribe"))) {
Tej Singhc9250ce2019-09-20 19:28:53 -0700355 {
356 std::lock_guard<std::mutex> lock(mShellSubscriberMutex);
357 if (mShellSubscriber == nullptr) {
358 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
359 }
Yao Chena80e5c02018-09-04 13:55:29 -0700360 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800361 int timeoutSec = -1;
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800362 if (argc >= 2) {
363 timeoutSec = atoi(utf8Args[1].c_str());
Yao Chen35cb8d62019-01-03 16:49:14 -0800364 }
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800365 mShellSubscriber->startNewSubscription(in, out, timeoutSec);
Yao Chena80e5c02018-09-04 13:55:29 -0700366 return NO_ERROR;
367 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700368 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700369
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700370 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700371 return NO_ERROR;
372}
373
Yao Chena80e5c02018-09-04 13:55:29 -0700374void StatsService::print_cmd_help(int out) {
375 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700376 "usage: adb shell cmd stats print-stats-log [tag_required] "
377 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700378 dprintf(out, "\n");
379 dprintf(out, "\n");
380 dprintf(out, "usage: adb shell cmd stats meminfo\n");
381 dprintf(out, "\n");
382 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
383 dprintf(out, " # adb shell stop\n");
384 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
385 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
386 dprintf(out, " # adb shell start\n");
387 dprintf(out, "\n");
388 dprintf(out, "\n");
389 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
390 dprintf(out, "\n");
391 dprintf(out, " Prints the UID, app name, version mapping.\n");
392 dprintf(out, " PKG Optional package name to print the uids of the package\n");
393 dprintf(out, "\n");
394 dprintf(out, "\n");
Tej Singh3be093b2020-03-04 20:08:38 -0800395 dprintf(out, "usage: adb shell cmd stats pull-source ATOM_TAG [PACKAGE] \n");
Yao Chena80e5c02018-09-04 13:55:29 -0700396 dprintf(out, "\n");
Tej Singh3be093b2020-03-04 20:08:38 -0800397 dprintf(out, " Prints the output of a pulled atom\n");
398 dprintf(out, " UID The atom to pull\n");
399 dprintf(out, " PACKAGE The package to pull from. Default is AID_SYSTEM\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700400 dprintf(out, "\n");
401 dprintf(out, "\n");
402 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
403 dprintf(out, "\n");
404 dprintf(out, " Flushes all data on memory to disk.\n");
405 dprintf(out, "\n");
406 dprintf(out, "\n");
407 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
408 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
409 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
410 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
411 dprintf(out, " uid is used.\n");
412 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
413 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
414 dprintf(out, "\n");
415 dprintf(out, "\n");
Tej Singh53f9dee2019-04-30 17:45:54 -0700416 dprintf(out,
417 "usage: adb shell cmd stats log-binary-push NAME VERSION STAGING ROLLBACK_ENABLED "
418 "LOW_LATENCY STATE EXPERIMENT_IDS\n");
419 dprintf(out, " Log a binary push state changed event.\n");
420 dprintf(out, " NAME The train name.\n");
421 dprintf(out, " VERSION The train version code.\n");
422 dprintf(out, " STAGING If this train requires a restart.\n");
423 dprintf(out, " ROLLBACK_ENABLED If rollback should be enabled for this install.\n");
424 dprintf(out, " LOW_LATENCY If the train requires low latency monitoring.\n");
425 dprintf(out, " STATE The status of the train push.\n");
426 dprintf(out, " Integer value of the enum in atoms.proto.\n");
427 dprintf(out, " EXPERIMENT_IDS Comma separated list of experiment ids.\n");
428 dprintf(out, " Leave blank for none.\n");
429 dprintf(out, "\n");
430 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700431 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
432 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
433 dprintf(out, "\n");
434 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
435 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
436 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
437 dprintf(out, "\n");
438 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
439 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
440 dprintf(out, " uid is used.\n");
441 dprintf(out, " NAME The per-uid name to use\n");
442 dprintf(out, "\n");
443 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
444 dprintf(out, "\n be removed from memory and disk!\n");
445 dprintf(out, "\n");
446 dprintf(out,
Bookatz3e906582018-12-10 17:26:58 -0800447 "usage: adb shell cmd stats dump-report [UID] NAME [--keep_data] "
448 "[--include_current_bucket] [--proto]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700449 dprintf(out, " Dump all metric data for a configuration.\n");
450 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
451 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
452 dprintf(out, " calling uid is used.\n");
453 dprintf(out, " NAME The name of the configuration\n");
Bookatz3e906582018-12-10 17:26:58 -0800454 dprintf(out, " --keep_data Do NOT erase the data upon dumping it.\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700455 dprintf(out, " --proto Print proto binary.\n");
456 dprintf(out, "\n");
457 dprintf(out, "\n");
458 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
459 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
460 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
461 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
462 dprintf(out, " calling uid is used.\n");
463 dprintf(out, " NAME The name of the configuration\n");
464 dprintf(out, "\n");
465 dprintf(out, "\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800466 dprintf(out,
467 "usage: adb shell cmd stats send-active-configs [--uid=UID] [--configs] "
468 "[NAME1] [NAME2] [NAME3..]\n");
469 dprintf(out, " Send a broadcast that informs the subscriber of the current active configs.\n");
470 dprintf(out, " --uid=UID The uid of the configurations. It is only possible to pass\n");
471 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
472 dprintf(out, " calling uid is used.\n");
473 dprintf(out, " --configs Send the list of configs in the name list instead of\n");
474 dprintf(out, " the currently active configs\n");
475 dprintf(out, " NAME LIST List of configuration names to be included in the broadcast.\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800476 dprintf(out, "\n");
477 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700478 dprintf(out, "usage: adb shell cmd stats print-stats\n");
479 dprintf(out, " Prints some basic stats.\n");
480 dprintf(out, " --proto Print proto binary instead of string format.\n");
481 dprintf(out, "\n");
482 dprintf(out, "\n");
483 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
484 dprintf(out, " Clear cached puller data.\n");
485 dprintf(out, "\n");
486 dprintf(out, "usage: adb shell cmd stats print-logs\n");
Ruchir Rastogi432f3702020-07-06 15:48:45 -0700487 dprintf(out, " Requires root privileges.\n");
488 dprintf(out, " Can be disabled by calling adb shell cmd stats print-logs 0\n");
David Chenadaf8b32017-11-03 15:42:08 -0700489}
490
Yao Chena80e5c02018-09-04 13:55:29 -0700491status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800492 string name;
493 bool good = false;
494 int uid;
495 const int argCount = args.size();
496 if (argCount == 2) {
497 // Automatically pick the UID
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800498 uid = AIBinder_getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800499 name.assign(args[1].c_str(), args[1].size());
500 good = true;
501 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800502 good = getUidFromArgs(args, 1, uid);
503 if (!good) {
504 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
505 "other UIDs on eng or userdebug builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800506 }
Bookatzd2386572018-12-14 15:53:14 -0800507 name.assign(args[2].c_str(), args[2].size());
David Chen1d7b0cd2017-11-15 14:20:04 -0800508 }
509 if (!good) {
510 print_cmd_help(out);
511 return UNKNOWN_ERROR;
512 }
David Chend37bc232018-04-12 18:05:11 -0700513 ConfigKey key(uid, StrToInt64(name));
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800514 shared_ptr<IPendingIntentRef> receiver = mConfigManager->GetConfigReceiver(key);
Jeffrey Huangad213742019-12-16 13:50:06 -0800515 if (receiver == nullptr) {
516 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str());
517 return UNKNOWN_ERROR;
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800518 } else if (receiver->sendDataBroadcast(mProcessor->getLastReportTimeNs(key)).isOk()) {
yro74fed972017-11-27 14:42:42 -0800519 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
520 args[2].c_str());
Jeffrey Huangad213742019-12-16 13:50:06 -0800521 } else {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800522 VLOG("StatsService::trigger broadcast failed to %s, %s", args[1].c_str(), args[2].c_str());
Jeffrey Huangad213742019-12-16 13:50:06 -0800523 return UNKNOWN_ERROR;
yro4d889e62017-11-17 15:44:48 -0800524 }
David Chenadaf8b32017-11-03 15:42:08 -0700525 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700526}
527
Tej Singh6ede28b2019-01-29 17:06:54 -0800528status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
529 const int argCount = args.size();
530 int uid;
531 vector<int64_t> configIds;
532 if (argCount == 1) {
533 // Automatically pick the uid and send a broadcast that has no active configs.
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800534 uid = AIBinder_getCallingUid();
Tej Singh6ede28b2019-01-29 17:06:54 -0800535 mProcessor->GetActiveConfigs(uid, configIds);
536 } else {
537 int curArg = 1;
538 if(args[curArg].find("--uid=") == 0) {
539 string uidArgStr(args[curArg].c_str());
540 string uidStr = uidArgStr.substr(6);
541 if (!getUidFromString(uidStr.c_str(), uid)) {
542 dprintf(out, "Invalid UID. Note that the config can only be set for "
543 "other UIDs on eng or userdebug builds.\n");
544 return UNKNOWN_ERROR;
545 }
546 curArg++;
547 } else {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800548 uid = AIBinder_getCallingUid();
Tej Singh6ede28b2019-01-29 17:06:54 -0800549 }
550 if (curArg == argCount || args[curArg] != "--configs") {
551 VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
552 mProcessor->GetActiveConfigs(uid, configIds);
553 } else {
554 // Flag specified, use the given list of configs.
555 curArg++;
556 for (int i = curArg; i < argCount; i++) {
557 char* endp;
558 int64_t configID = strtoll(args[i].c_str(), &endp, 10);
559 if (endp == args[i].c_str() || *endp != '\0') {
560 dprintf(out, "Error parsing config ID.\n");
561 return UNKNOWN_ERROR;
562 }
563 VLOG("Adding config id %ld", static_cast<long>(configID));
564 configIds.push_back(configID);
565 }
566 }
567 }
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800568 shared_ptr<IPendingIntentRef> receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
Jeffrey Huang47537a12020-01-06 15:35:34 -0800569 if (receiver == nullptr) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800570 VLOG("Could not find receiver for uid %d", uid);
Jeffrey Huang47537a12020-01-06 15:35:34 -0800571 return UNKNOWN_ERROR;
572 } else if (receiver->sendActiveConfigsChangedBroadcast(configIds).isOk()) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800573 VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
Jeffrey Huang47537a12020-01-06 15:35:34 -0800574 } else {
575 VLOG("StatsService::trigger active configs changed broadcast failed for uid %d", uid);
576 return UNKNOWN_ERROR;
Tej Singh6ede28b2019-01-29 17:06:54 -0800577 }
578 return NO_ERROR;
579}
580
Yao Chena80e5c02018-09-04 13:55:29 -0700581status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700582 const int argCount = args.size();
583 if (argCount >= 2) {
584 if (args[1] == "update" || args[1] == "remove") {
585 bool good = false;
586 int uid = -1;
587 string name;
588
589 if (argCount == 3) {
590 // Automatically pick the UID
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800591 uid = AIBinder_getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700592 name.assign(args[2].c_str(), args[2].size());
593 good = true;
594 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800595 good = getUidFromArgs(args, 2, uid);
596 if (!good) {
597 dprintf(err, "Invalid UID. Note that the config can only be set for "
598 "other UIDs on eng or userdebug builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700599 }
Bookatzd2386572018-12-14 15:53:14 -0800600 name.assign(args[3].c_str(), args[3].size());
yroe5f82922018-01-22 18:37:27 -0800601 } else if (argCount == 2 && args[1] == "remove") {
602 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700603 }
604
605 if (!good) {
606 // If arg parsing failed, print the help text and return an error.
607 print_cmd_help(out);
608 return UNKNOWN_ERROR;
609 }
610
611 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800612 char* endp;
613 int64_t configID = strtoll(name.c_str(), &endp, 10);
614 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700615 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800616 return UNKNOWN_ERROR;
617 }
618
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700619 // Read stream into buffer.
620 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700621 if (!android::base::ReadFdToString(in, &buffer)) {
622 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700623 return UNKNOWN_ERROR;
624 }
625
626 // Parse buffer.
627 StatsdConfig config;
628 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700629 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700630 return UNKNOWN_ERROR;
631 }
632
633 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800634 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700635 } else {
yro74fed972017-11-27 14:42:42 -0800636 if (argCount == 2) {
637 cmd_remove_all_configs(out);
638 } else {
639 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800640 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800641 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700642 }
643
644 return NO_ERROR;
645 }
David Chen0656b7a2017-09-13 15:53:39 -0700646 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700647 print_cmd_help(out);
648 return UNKNOWN_ERROR;
649}
650
Bookatzff71cad2018-09-20 17:17:49 -0700651status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700652 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800653 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700654 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800655 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700656 bool includeCurrentBucket = false;
Bookatz3e906582018-12-10 17:26:58 -0800657 bool eraseData = true;
Yao Chen729093d2017-10-16 10:33:26 -0700658 int uid;
659 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800660 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
661 proto = true;
662 argCount -= 1;
663 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700664 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
665 includeCurrentBucket = true;
666 argCount -= 1;
667 }
Bookatz3e906582018-12-10 17:26:58 -0800668 if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
669 eraseData = false;
670 argCount -= 1;
671 }
Yao Chen729093d2017-10-16 10:33:26 -0700672 if (argCount == 2) {
673 // Automatically pick the UID
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800674 uid = AIBinder_getCallingUid();
Yao Chen5154a3792017-10-30 22:57:06 -0700675 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700676 good = true;
677 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800678 good = getUidFromArgs(args, 1, uid);
679 if (!good) {
680 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
681 "other UIDs on eng or userdebug builds.\n");
Yao Chen729093d2017-10-16 10:33:26 -0700682 }
Bookatzd2386572018-12-14 15:53:14 -0800683 name.assign(args[2].c_str(), args[2].size());
Yao Chen729093d2017-10-16 10:33:26 -0700684 }
685 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800686 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800687 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000688 includeCurrentBucket, eraseData, ADB_DUMP,
689 NO_TIME_CONSTRAINTS,
690 &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800691 if (proto) {
692 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700693 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800694 }
695 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700696 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800697 }
Yao Chen729093d2017-10-16 10:33:26 -0700698 return android::OK;
699 } else {
700 // If arg parsing failed, print the help text and return an error.
701 print_cmd_help(out);
702 return UNKNOWN_ERROR;
703 }
704 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700705 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700706 return UNKNOWN_ERROR;
707 }
708}
709
Yao Chena80e5c02018-09-04 13:55:29 -0700710status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700711 int argCount = args.size();
712 bool proto = false;
713 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
714 proto = true;
715 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800716 }
Yao Chenb3561512017-11-21 18:07:17 -0800717 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700718 if (proto) {
719 vector<uint8_t> data;
720 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
721 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700722 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700723 }
724
725 } else {
726 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
727 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700728 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700729 mProcessor->GetMetricsSize(key));
730 }
731 statsdStats.dumpStats(out);
732 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800733 return NO_ERROR;
734}
735
Yao Chena80e5c02018-09-04 13:55:29 -0700736status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800737 if (args.size() > 1) {
738 string pkg;
739 pkg.assign(args[1].c_str(), args[1].size());
740 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700741 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800742 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700743 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800744 }
Yao Chena80e5c02018-09-04 13:55:29 -0700745 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800746 } else {
747 mUidMap->printUidMap(out);
748 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700749 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700750}
751
Yao Chena80e5c02018-09-04 13:55:29 -0700752status_t StatsService::cmd_write_data_to_disk(int out) {
753 dprintf(out, "Writing data to disk\n");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000754 mProcessor->WriteDataToDisk(ADB_DUMP, NO_TIME_CONSTRAINTS);
yro947fbce2017-11-15 22:50:23 -0800755 return NO_ERROR;
756}
757
Yao Chena80e5c02018-09-04 13:55:29 -0700758status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800759 bool good = false;
760 int32_t uid;
761 int32_t label;
762 int32_t state;
763 const int argCount = args.size();
764 if (argCount == 3) {
765 // Automatically pick the UID
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800766 uid = AIBinder_getCallingUid();
Bookatzb223c4e2018-02-01 15:35:04 -0800767 label = atoi(args[1].c_str());
768 state = atoi(args[2].c_str());
769 good = true;
770 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800771 good = getUidFromArgs(args, 1, uid);
772 if (!good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700773 dprintf(out,
Bookatzd2386572018-12-14 15:53:14 -0800774 "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
775 "done for other UIDs on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800776 }
Bookatzd2386572018-12-14 15:53:14 -0800777 label = atoi(args[2].c_str());
778 state = atoi(args[3].c_str());
Bookatzb223c4e2018-02-01 15:35:04 -0800779 }
780 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700781 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800782 android::os::statsd::util::stats_write(
783 android::os::statsd::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800784 } else {
785 print_cmd_help(out);
786 return UNKNOWN_ERROR;
787 }
788 return NO_ERROR;
789}
790
Tej Singh53f9dee2019-04-30 17:45:54 -0700791status_t StatsService::cmd_log_binary_push(int out, const Vector<String8>& args) {
792 // Security checks are done in the sendBinaryPushStateChanged atom.
793 const int argCount = args.size();
794 if (argCount != 7 && argCount != 8) {
795 dprintf(out, "Incorrect number of argument supplied\n");
796 return UNKNOWN_ERROR;
797 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800798 string trainName = string(args[1].c_str());
Tej Singh53f9dee2019-04-30 17:45:54 -0700799 int64_t trainVersion = strtoll(args[2].c_str(), nullptr, 10);
Tej Singh53f9dee2019-04-30 17:45:54 -0700800 int32_t state = atoi(args[6].c_str());
801 vector<int64_t> experimentIds;
802 if (argCount == 8) {
803 vector<string> experimentIdsString = android::base::Split(string(args[7].c_str()), ",");
804 for (string experimentIdString : experimentIdsString) {
805 int64_t experimentId = strtoll(experimentIdString.c_str(), nullptr, 10);
806 experimentIds.push_back(experimentId);
807 }
808 }
809 dprintf(out, "Logging BinaryPushStateChanged\n");
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800810 vector<uint8_t> experimentIdBytes;
811 writeExperimentIdsToProto(experimentIds, &experimentIdBytes);
812 LogEvent event(trainName, trainVersion, args[3], args[4], args[5], state, experimentIdBytes, 0);
813 mProcessor->OnLogEvent(&event);
Tej Singh53f9dee2019-04-30 17:45:54 -0700814 return NO_ERROR;
815}
816
Yao Chena80e5c02018-09-04 13:55:29 -0700817status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700818 int s = atoi(args[1].c_str());
Tej Singh3be093b2020-03-04 20:08:38 -0800819 vector<int32_t> uids;
820 if (args.size() > 2) {
821 string package = string(args[2].c_str());
822 auto it = UidMap::sAidToUidMapping.find(package);
823 if (it != UidMap::sAidToUidMapping.end()) {
824 uids.push_back(it->second);
825 } else {
826 set<int32_t> uids_set = mUidMap->getAppUid(package);
827 uids.insert(uids.end(), uids_set.begin(), uids_set.end());
828 }
829 } else {
830 uids.push_back(AID_SYSTEM);
831 }
832 vector<shared_ptr<LogEvent>> stats;
Tej Singh7b975a82020-05-11 11:05:08 -0700833 if (mPullerManager->Pull(s, uids, getElapsedRealtimeNs(), &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700834 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700835 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700836 }
Yao Chena80e5c02018-09-04 13:55:29 -0700837 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700838 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700839 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700840 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700841}
842
Yao Chena80e5c02018-09-04 13:55:29 -0700843status_t StatsService::cmd_remove_all_configs(int out) {
844 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800845 VLOG("StatsService::cmd_remove_all_configs was called");
846 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800847 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800848 return NO_ERROR;
849}
850
Yao Chena80e5c02018-09-04 13:55:29 -0700851status_t StatsService::cmd_dump_memory_info(int out) {
852 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800853 return NO_ERROR;
854}
855
Yao Chena80e5c02018-09-04 13:55:29 -0700856status_t StatsService::cmd_clear_puller_cache(int out) {
Yangster-mac932ecec2018-02-01 10:23:52 -0800857 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800858 AIBinder_getCallingPid(), AIBinder_getCallingUid());
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -0800859 if (checkPermission(kPermissionDump)) {
Chenjie Yue2219202018-06-08 10:07:51 -0700860 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700861 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800862 return NO_ERROR;
863 } else {
864 return PERMISSION_DENIED;
865 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800866}
867
Yao Chena80e5c02018-09-04 13:55:29 -0700868status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Ruchir Rastogi432f3702020-07-06 15:48:45 -0700869 Status status = checkUid(AID_ROOT);
870 if (!status.isOk()) {
Yao Chen876889c2018-05-02 11:16:16 -0700871 return PERMISSION_DENIED;
872 }
Ruchir Rastogi432f3702020-07-06 15:48:45 -0700873
874 VLOG("StatsService::cmd_print_logs with pid %i, uid %i", AIBinder_getCallingPid(),
875 AIBinder_getCallingUid());
876 bool enabled = true;
877 if (args.size() >= 2) {
878 enabled = atoi(args[1].c_str()) != 0;
879 }
880 mProcessor->setPrintLogs(enabled);
881 return NO_ERROR;
Yao Chen876889c2018-05-02 11:16:16 -0700882}
883
Bookatzd2386572018-12-14 15:53:14 -0800884bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800885 return getUidFromString(args[uidArgIndex].c_str(), uid);
886}
887
888bool StatsService::getUidFromString(const char* s, int32_t& uid) {
Bookatzd2386572018-12-14 15:53:14 -0800889 if (*s == '\0') {
890 return false;
891 }
892 char* endc = NULL;
893 int64_t longUid = strtol(s, &endc, 0);
894 if (*endc != '\0') {
895 return false;
896 }
897 int32_t goodUid = static_cast<int32_t>(longUid);
898 if (longUid < 0 || static_cast<uint64_t>(longUid) != static_cast<uid_t>(goodUid)) {
899 return false; // It was not of uid_t type.
900 }
901 uid = goodUid;
902
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800903 int32_t callingUid = AIBinder_getCallingUid();
Bookatzd2386572018-12-14 15:53:14 -0800904 return mEngBuild // UserDebug/EngBuild are allowed to impersonate uids.
905 || (callingUid == goodUid) // Anyone can 'impersonate' themselves.
906 || (callingUid == AID_ROOT && goodUid == AID_SHELL); // ROOT can impersonate SHELL.
907}
908
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800909Status StatsService::informAllUidData(const ScopedFileDescriptor& fd) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600910 ENFORCE_UID(AID_SYSTEM);
Max Dashouk11e0d402019-05-16 16:58:07 -0700911 // Read stream into buffer.
912 string buffer;
913 if (!android::base::ReadFdToString(fd.get(), &buffer)) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800914 return exception(EX_ILLEGAL_ARGUMENT, "Failed to read all data from the pipe.");
Max Dashouk11e0d402019-05-16 16:58:07 -0700915 }
Jeff Sharkey6b649252018-04-16 09:50:22 -0600916
Max Dashouk11e0d402019-05-16 16:58:07 -0700917 // Parse buffer.
918 UidData uidData;
919 if (!uidData.ParseFromString(buffer)) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800920 return exception(EX_ILLEGAL_ARGUMENT, "Error parsing proto stream for UidData.");
Max Dashouk11e0d402019-05-16 16:58:07 -0700921 }
David Chende701692017-10-05 13:16:02 -0700922
Max Dashouk11e0d402019-05-16 16:58:07 -0700923 vector<String16> versionStrings;
924 vector<String16> installers;
925 vector<String16> packageNames;
926 vector<int32_t> uids;
927 vector<int64_t> versions;
928
929 const auto numEntries = uidData.app_info_size();
930 versionStrings.reserve(numEntries);
931 installers.reserve(numEntries);
932 packageNames.reserve(numEntries);
933 uids.reserve(numEntries);
934 versions.reserve(numEntries);
935
936 for (const auto& appInfo: uidData.app_info()) {
937 packageNames.emplace_back(String16(appInfo.package_name().c_str()));
938 uids.push_back(appInfo.uid());
939 versions.push_back(appInfo.version());
940 versionStrings.emplace_back(String16(appInfo.version_string().c_str()));
941 installers.emplace_back(String16(appInfo.installer().c_str()));
942 }
943
944 mUidMap->updateMap(getElapsedRealtimeNs(),
945 uids,
946 versions,
947 versionStrings,
948 packageNames,
949 installers);
950
Tej Singhe678cb72020-04-14 16:23:30 -0700951 mBootCompleteTrigger.markComplete(kUidMapReceivedTag);
Max Dashouk11e0d402019-05-16 16:58:07 -0700952 VLOG("StatsService::informAllUidData UidData proto parsed successfully.");
David Chende701692017-10-05 13:16:02 -0700953 return Status::ok();
954}
955
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800956Status StatsService::informOnePackage(const string& app, int32_t uid, int64_t version,
957 const string& versionString, const string& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600958 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700959
Jeff Sharkey6b649252018-04-16 09:50:22 -0600960 VLOG("StatsService::informOnePackage was called");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800961 String16 utf16App = String16(app.c_str());
962 String16 utf16VersionString = String16(versionString.c_str());
963 String16 utf16Installer = String16(installer.c_str());
964
965 mUidMap->updateApp(getElapsedRealtimeNs(), utf16App, uid, version, utf16VersionString,
966 utf16Installer);
David Chende701692017-10-05 13:16:02 -0700967 return Status::ok();
968}
969
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800970Status StatsService::informOnePackageRemoved(const string& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600971 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700972
Jeff Sharkey6b649252018-04-16 09:50:22 -0600973 VLOG("StatsService::informOnePackageRemoved was called");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800974 String16 utf16App = String16(app.c_str());
975 mUidMap->removeApp(getElapsedRealtimeNs(), utf16App, uid);
yro01924022018-02-20 18:20:49 -0800976 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -0700977 return Status::ok();
978}
979
Yao Chenef99c4f2017-09-22 16:26:54 -0700980Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600981 ENFORCE_UID(AID_SYSTEM);
982
yro74fed972017-11-27 14:42:42 -0800983 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700984 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800985 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
986 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
987 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -0800988 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -0800989 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -0800990 } else {
991 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
992 }
Bookatz1b0b1142017-09-08 11:58:42 -0700993 return Status::ok();
994}
995
Yangster-mac932ecec2018-02-01 10:23:52 -0800996Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600997 ENFORCE_UID(AID_SYSTEM);
998
Yangster-mac932ecec2018-02-01 10:23:52 -0800999 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -07001000 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -08001001 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
1002 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
1003 if (alarmSet.size() > 0) {
1004 VLOG("Found periodic alarm fired.");
1005 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
1006 } else {
1007 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
1008 }
1009 return Status::ok();
1010}
1011
Yao Chenef99c4f2017-09-22 16:26:54 -07001012Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001013 ENFORCE_UID(AID_SYSTEM);
1014
yro74fed972017-11-27 14:42:42 -08001015 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -07001016 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -08001017 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -07001018 return Status::ok();
1019}
1020
Yao Chenef99c4f2017-09-22 16:26:54 -07001021Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001022 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001023
1024 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -08001025 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -07001026 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001027 return Status::ok();
1028}
1029
Yangster-mac892f3d32018-05-02 14:16:48 -07001030Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001031 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -07001032 VLOG("StatsService::informDeviceShutdown");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001033 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001034 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
Jeffrey Huangb8f54032020-03-23 13:42:42 -07001035 mProcessor->SaveMetadataToDisk(getWallClockNs(), getElapsedRealtimeNs());
yro947fbce2017-11-15 22:50:23 -08001036 return Status::ok();
1037}
1038
Yao Chenef99c4f2017-09-22 16:26:54 -07001039void StatsService::sayHiToStatsCompanion() {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001040 shared_ptr<IStatsCompanionService> statsCompanion = getStatsCompanionService();
Bookatzb487b552017-09-18 11:26:01 -07001041 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -08001042 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -07001043 statsCompanion->statsdReady();
1044 } else {
yro74fed972017-11-27 14:42:42 -08001045 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -07001046 }
1047}
1048
Yao Chenef99c4f2017-09-22 16:26:54 -07001049Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001050 ENFORCE_UID(AID_SYSTEM);
1051
yro74fed972017-11-27 14:42:42 -08001052 VLOG("StatsService::statsCompanionReady was called");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001053 shared_ptr<IStatsCompanionService> statsCompanion = getStatsCompanionService();
Bookatzb487b552017-09-18 11:26:01 -07001054 if (statsCompanion == nullptr) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001055 return exception(EX_NULL_POINTER,
1056 "StatsCompanion unavailable despite it contacting statsd.");
Bookatzb487b552017-09-18 11:26:01 -07001057 }
yro74fed972017-11-27 14:42:42 -08001058 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001059 AIBinder_linkToDeath(statsCompanion->asBinder().get(),
1060 mStatsCompanionServiceDeathRecipient.get(), this);
Chenjie Yue2219202018-06-08 10:07:51 -07001061 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -08001062 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
1063 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -07001064 return Status::ok();
1065}
1066
Jeffrey Huangd8f53302020-04-06 18:09:55 -07001067Status StatsService::bootCompleted() {
1068 ENFORCE_UID(AID_SYSTEM);
1069
1070 VLOG("StatsService::bootCompleted was called");
Tej Singhe678cb72020-04-14 16:23:30 -07001071 mBootCompleteTrigger.markComplete(kBootCompleteTag);
Jeffrey Huangd8f53302020-04-06 18:09:55 -07001072 return Status::ok();
1073}
1074
Joe Onorato9fc9edf2017-10-15 20:08:52 -07001075void StatsService::Startup() {
1076 mConfigManager->Startup();
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001077 mProcessor->LoadActiveConfigsFromDisk();
Jeffrey Huang475677e2020-03-30 19:52:07 -07001078 mProcessor->LoadMetadataFromDisk(getWallClockNs(), getElapsedRealtimeNs());
Bookatz906a35c2017-09-20 15:26:44 -07001079}
1080
Yangster-mac97e7d202018-10-09 11:05:39 -07001081void StatsService::Terminate() {
1082 ALOGI("StatsService::Terminating");
1083 if (mProcessor != nullptr) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001084 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001085 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
Jeffrey Huangb8f54032020-03-23 13:42:42 -07001086 mProcessor->SaveMetadataToDisk(getWallClockNs(), getElapsedRealtimeNs());
Yangster-mac97e7d202018-10-09 11:05:39 -07001087 }
1088}
1089
Yao Chen0f861862019-03-27 11:51:15 -07001090// Test only interface!!!
Yao Chen3ff3a492018-08-06 16:17:37 -07001091void StatsService::OnLogEvent(LogEvent* event) {
1092 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -07001093 if (mShellSubscriber != nullptr) {
1094 mShellSubscriber->onLogEvent(*event);
1095 }
Bookatz906a35c2017-09-20 15:26:44 -07001096}
1097
Jooyung Han592d6bf2020-02-22 00:46:52 +09001098Status StatsService::getData(int64_t key, const int32_t callingUid, vector<uint8_t>* output) {
Jeffrey Huang04f948b2020-01-07 10:05:25 -08001099 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001100
Jeffrey Huang04f948b2020-01-07 10:05:25 -08001101 VLOG("StatsService::getData with Uid %i", callingUid);
1102 ConfigKey configKey(callingUid, key);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001103 // The dump latency does not matter here since we do not include the current bucket, we do not
1104 // need to pull any new data anyhow.
David Chen56ae0d92018-05-11 16:00:22 -07001105 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
Jooyung Han592d6bf2020-02-22 00:46:52 +09001106 true /* erase_data */, GET_DATA_CALLED, FAST, output);
Bookatz4f716292018-04-10 17:15:12 -07001107 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001108}
1109
Jooyung Han592d6bf2020-02-22 00:46:52 +09001110Status StatsService::getMetadata(vector<uint8_t>* output) {
Jeffrey Huang9613a972020-01-07 10:05:03 -08001111 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001112
Jooyung Han592d6bf2020-02-22 00:46:52 +09001113 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
Bookatz4f716292018-04-10 17:15:12 -07001114 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -08001115}
1116
Jooyung Han592d6bf2020-02-22 00:46:52 +09001117Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001118 const int32_t callingUid) {
1119 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001120
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001121 if (addConfigurationChecked(callingUid, key, config)) {
David Chen661f7912018-01-22 17:46:24 -08001122 return Status::ok();
1123 } else {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001124 return exception(EX_ILLEGAL_ARGUMENT, "Could not parse malformatted StatsdConfig.");
David Chen661f7912018-01-22 17:46:24 -08001125 }
1126}
1127
Jooyung Han592d6bf2020-02-22 00:46:52 +09001128bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
David Chen9fdd4032018-03-20 14:38:56 -07001129 ConfigKey configKey(uid, key);
1130 StatsdConfig cfg;
1131 if (config.size() > 0) { // If the config is empty, skip parsing.
1132 if (!cfg.ParseFromArray(&config[0], config.size())) {
1133 return false;
1134 }
1135 }
1136 mConfigManager->UpdateConfig(configKey, cfg);
1137 return true;
1138}
1139
Jeffrey Huangad213742019-12-16 13:50:06 -08001140Status StatsService::removeDataFetchOperation(int64_t key,
1141 const int32_t callingUid) {
1142 ENFORCE_UID(AID_SYSTEM);
1143 ConfigKey configKey(callingUid, key);
Bookatz4f716292018-04-10 17:15:12 -07001144 mConfigManager->RemoveConfigReceiver(configKey);
1145 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -08001146}
1147
Jeff Sharkey6b649252018-04-16 09:50:22 -06001148Status StatsService::setDataFetchOperation(int64_t key,
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001149 const shared_ptr<IPendingIntentRef>& pir,
Jeffrey Huangad213742019-12-16 13:50:06 -08001150 const int32_t callingUid) {
1151 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001152
Jeffrey Huangad213742019-12-16 13:50:06 -08001153 ConfigKey configKey(callingUid, key);
1154 mConfigManager->SetConfigReceiver(configKey, pir);
David Chen48944902018-05-03 10:29:11 -07001155 if (StorageManager::hasConfigMetricsReport(configKey)) {
1156 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
1157 configKey.ToString().c_str());
1158 mProcessor->noteOnDiskData(configKey);
1159 }
Bookatz4f716292018-04-10 17:15:12 -07001160 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001161}
1162
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001163Status StatsService::setActiveConfigsChangedOperation(const shared_ptr<IPendingIntentRef>& pir,
Jeffrey Huang47537a12020-01-06 15:35:34 -08001164 const int32_t callingUid,
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001165 vector<int64_t>* output) {
Jeffrey Huang47537a12020-01-06 15:35:34 -08001166 ENFORCE_UID(AID_SYSTEM);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001167
Jeffrey Huang47537a12020-01-06 15:35:34 -08001168 mConfigManager->SetActiveConfigsChangedReceiver(callingUid, pir);
Tej Singh6ede28b2019-01-29 17:06:54 -08001169 if (output != nullptr) {
Jeffrey Huang47537a12020-01-06 15:35:34 -08001170 mProcessor->GetActiveConfigs(callingUid, *output);
Tej Singh6ede28b2019-01-29 17:06:54 -08001171 } else {
1172 ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
1173 }
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001174 return Status::ok();
1175}
1176
Jeffrey Huang47537a12020-01-06 15:35:34 -08001177Status StatsService::removeActiveConfigsChangedOperation(const int32_t callingUid) {
1178 ENFORCE_UID(AID_SYSTEM);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001179
Jeffrey Huang47537a12020-01-06 15:35:34 -08001180 mConfigManager->RemoveActiveConfigsChangedReceiver(callingUid);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001181 return Status::ok();
1182}
1183
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001184Status StatsService::removeConfiguration(int64_t key, const int32_t callingUid) {
1185 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001186
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001187 ConfigKey configKey(callingUid, key);
Bookatz4f716292018-04-10 17:15:12 -07001188 mConfigManager->RemoveConfig(configKey);
Bookatz4f716292018-04-10 17:15:12 -07001189 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001190}
1191
Bookatzc6977972018-01-16 16:55:05 -08001192Status StatsService::setBroadcastSubscriber(int64_t configId,
1193 int64_t subscriberId,
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001194 const shared_ptr<IPendingIntentRef>& pir,
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001195 const int32_t callingUid) {
1196 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001197
Bookatzc6977972018-01-16 16:55:05 -08001198 VLOG("StatsService::setBroadcastSubscriber called.");
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001199 ConfigKey configKey(callingUid, configId);
Bookatz4f716292018-04-10 17:15:12 -07001200 SubscriberReporter::getInstance()
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001201 .setBroadcastSubscriber(configKey, subscriberId, pir);
Bookatz4f716292018-04-10 17:15:12 -07001202 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001203}
1204
1205Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001206 int64_t subscriberId,
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001207 const int32_t callingUid) {
1208 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001209
Bookatzc6977972018-01-16 16:55:05 -08001210 VLOG("StatsService::unsetBroadcastSubscriber called.");
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001211 ConfigKey configKey(callingUid, configId);
Bookatz4f716292018-04-10 17:15:12 -07001212 SubscriberReporter::getInstance()
1213 .unsetBroadcastSubscriber(configKey, subscriberId);
1214 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001215}
1216
Jeffrey Huangd7fda532020-04-06 18:19:46 -07001217Status StatsService::allPullersFromBootRegistered() {
1218 ENFORCE_UID(AID_SYSTEM);
1219
1220 VLOG("StatsService::allPullersFromBootRegistered was called");
Tej Singhe678cb72020-04-14 16:23:30 -07001221 mBootCompleteTrigger.markComplete(kAllPullersRegisteredTag);
Jeffrey Huangd7fda532020-04-06 18:19:46 -07001222 return Status::ok();
1223}
1224
Tej Singh72a70a82020-02-26 23:46:29 -08001225Status StatsService::registerPullAtomCallback(int32_t uid, int32_t atomTag, int64_t coolDownMillis,
1226 int64_t timeoutMillis,
1227 const std::vector<int32_t>& additiveFields,
1228 const shared_ptr<IPullAtomCallback>& pullerCallback) {
Tej Singh6a5c9432019-10-11 11:07:06 -07001229 ENFORCE_UID(AID_SYSTEM);
Tej Singhb7802512019-12-04 17:57:04 -08001230 VLOG("StatsService::registerPullAtomCallback called.");
Tej Singh72a70a82020-02-26 23:46:29 -08001231 mPullerManager->RegisterPullAtomCallback(uid, atomTag, MillisToNano(coolDownMillis),
1232 MillisToNano(timeoutMillis), additiveFields,
Tej Singhb7802512019-12-04 17:57:04 -08001233 pullerCallback);
1234 return Status::ok();
1235}
1236
Tej Singh73597dc2020-03-13 18:42:40 -07001237Status StatsService::registerNativePullAtomCallback(
1238 int32_t atomTag, int64_t coolDownMillis, int64_t timeoutMillis,
1239 const std::vector<int32_t>& additiveFields,
1240 const shared_ptr<IPullAtomCallback>& pullerCallback) {
Tej Singh10458ec2020-03-17 11:04:02 -07001241 if (!checkPermission(kPermissionRegisterPullAtom)) {
1242 return exception(
1243 EX_SECURITY,
1244 StringPrintf("Uid %d does not have the %s permission when registering atom %d",
1245 AIBinder_getCallingUid(), kPermissionRegisterPullAtom, atomTag));
1246 }
Tej Singhb7802512019-12-04 17:57:04 -08001247 VLOG("StatsService::registerNativePullAtomCallback called.");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001248 int32_t uid = AIBinder_getCallingUid();
Tej Singh73597dc2020-03-13 18:42:40 -07001249 mPullerManager->RegisterPullAtomCallback(uid, atomTag, MillisToNano(coolDownMillis),
1250 MillisToNano(timeoutMillis), additiveFields,
Tej Singh6a5c9432019-10-11 11:07:06 -07001251 pullerCallback);
Tej Singh59184292019-10-11 11:07:06 -07001252 return Status::ok();
1253}
1254
Tej Singhfa1c1372019-12-05 20:36:54 -08001255Status StatsService::unregisterPullAtomCallback(int32_t uid, int32_t atomTag) {
1256 ENFORCE_UID(AID_SYSTEM);
1257 VLOG("StatsService::unregisterPullAtomCallback called.");
1258 mPullerManager->UnregisterPullAtomCallback(uid, atomTag);
1259 return Status::ok();
1260}
1261
Tej Singh8f358602020-01-15 16:05:39 -08001262Status StatsService::unregisterNativePullAtomCallback(int32_t atomTag) {
Tej Singh10458ec2020-03-17 11:04:02 -07001263 if (!checkPermission(kPermissionRegisterPullAtom)) {
1264 return exception(
1265 EX_SECURITY,
1266 StringPrintf("Uid %d does not have the %s permission when unregistering atom %d",
1267 AIBinder_getCallingUid(), kPermissionRegisterPullAtom, atomTag));
1268 }
Tej Singh8f358602020-01-15 16:05:39 -08001269 VLOG("StatsService::unregisterNativePullAtomCallback called.");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001270 int32_t uid = AIBinder_getCallingUid();
Tej Singh8f358602020-01-15 16:05:39 -08001271 mPullerManager->UnregisterPullAtomCallback(uid, atomTag);
1272 return Status::ok();
1273}
1274
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001275Status StatsService::getRegisteredExperimentIds(std::vector<int64_t>* experimentIdsOut) {
Jeffrey Huang80c9a972020-01-07 10:04:27 -08001276 ENFORCE_UID(AID_SYSTEM);
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001277 // TODO: add verifier permission
1278
Jonathan Nguyen703c42f2020-02-04 15:54:26 -08001279 experimentIdsOut->clear();
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001280 // Read the latest train info
Jonathan Nguyen703c42f2020-02-04 15:54:26 -08001281 vector<InstallTrainInfo> trainInfoList = StorageManager::readAllTrainInfo();
1282 if (trainInfoList.empty()) {
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001283 // No train info means no experiment IDs, return an empty list
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001284 return Status::ok();
1285 }
1286
1287 // Copy the experiment IDs to the out vector
Jonathan Nguyen703c42f2020-02-04 15:54:26 -08001288 for (InstallTrainInfo& trainInfo : trainInfoList) {
1289 experimentIdsOut->insert(experimentIdsOut->end(),
1290 trainInfo.experimentIds.begin(),
1291 trainInfo.experimentIds.end());
1292 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001293 return Status::ok();
1294}
1295
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001296void StatsService::statsCompanionServiceDied(void* cookie) {
1297 auto thiz = static_cast<StatsService*>(cookie);
1298 thiz->statsCompanionServiceDiedImpl();
1299}
1300
1301void StatsService::statsCompanionServiceDiedImpl() {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001302 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001303 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1304 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001305 ALOGW("Reset statsd upon system server restarts.");
Tej Singhf53d4452019-05-09 18:17:59 -07001306 int64_t systemServerRestartNs = getElapsedRealtimeNs();
Jeffrey Huangb8f54032020-03-23 13:42:42 -07001307 ProtoOutputStream activeConfigsProto;
Tej Singhf53d4452019-05-09 18:17:59 -07001308 mProcessor->WriteActiveConfigsToProtoOutputStream(systemServerRestartNs,
Jeffrey Huangb8f54032020-03-23 13:42:42 -07001309 STATSCOMPANION_DIED, &activeConfigsProto);
1310 metadata::StatsMetadataList metadataList;
1311 mProcessor->WriteMetadataToProto(getWallClockNs(),
1312 systemServerRestartNs, &metadataList);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001313 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED, FAST);
Yangster-mac892f3d32018-05-02 14:16:48 -07001314 mProcessor->resetConfigs();
Tej Singhf53d4452019-05-09 18:17:59 -07001315
1316 std::string serializedActiveConfigs;
Jeffrey Huangb8f54032020-03-23 13:42:42 -07001317 if (activeConfigsProto.serializeToString(&serializedActiveConfigs)) {
Tej Singhf53d4452019-05-09 18:17:59 -07001318 ActiveConfigList activeConfigs;
1319 if (activeConfigs.ParseFromString(serializedActiveConfigs)) {
1320 mProcessor->SetConfigsActiveState(activeConfigs, systemServerRestartNs);
1321 }
1322 }
Jeffrey Huang475677e2020-03-30 19:52:07 -07001323 mProcessor->SetMetadataState(metadataList, getWallClockNs(), systemServerRestartNs);
Yangster-mac892f3d32018-05-02 14:16:48 -07001324 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001325 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1326 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001327 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001328}
1329
Yao Chenef99c4f2017-09-22 16:26:54 -07001330} // namespace statsd
1331} // namespace os
1332} // namespace android