blob: 68c2dd56ef137a701d9431391bc83996395fe1f3 [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,
Tej Singh44024862020-07-14 23:16:24 -070094 [this](const shared_ptr<IStatsCompanionService>& /*sc*/, int64_t timeMillis) {
95 mProcessor->setAnomalyAlarm(timeMillis);
96 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
Yao Chen0f861862019-03-27 11:51:15 -070097 },
Tej Singh44024862020-07-14 23:16:24 -070098 [this](const shared_ptr<IStatsCompanionService>& /*sc*/) {
99 mProcessor->cancelAnomalyAlarm();
100 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
Yao Chen0f861862019-03-27 11:51:15 -0700101 })),
102 mPeriodicAlarmMonitor(new AlarmMonitor(
103 MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800104 [](const shared_ptr<IStatsCompanionService>& sc, int64_t timeMillis) {
Yao Chen0f861862019-03-27 11:51:15 -0700105 if (sc != nullptr) {
106 sc->setAlarmForSubscriberTriggering(timeMillis);
107 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
108 }
109 },
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800110 [](const shared_ptr<IStatsCompanionService>& sc) {
Yao Chen0f861862019-03-27 11:51:15 -0700111 if (sc != nullptr) {
112 sc->cancelAlarmForSubscriberTriggering();
113 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
114 }
115 })),
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800116 mEventQueue(queue),
Tej Singhe678cb72020-04-14 16:23:30 -0700117 mBootCompleteTrigger({kBootCompleteTag, kUidMapReceivedTag, kAllPullersRegisteredTag},
118 [this]() { mProcessor->onStatsdInitCompleted(getElapsedRealtimeNs()); }),
Tej Singh769f35f2020-04-11 03:39:12 -0700119 mStatsCompanionServiceDeathRecipient(
120 AIBinder_DeathRecipient_new(StatsService::statsCompanionServiceDied)) {
Yao Chen4ce07292019-02-13 13:06:36 -0800121 mUidMap = UidMap::getInstance();
Chenjie Yue2219202018-06-08 10:07:51 -0700122 mPullerManager = new StatsPullerManager();
Chenjie Yu80f91122018-01-31 20:24:50 -0800123 StatsPuller::SetUidMap(mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700124 mConfigManager = new ConfigManager();
Chenjie Yue2219202018-06-08 10:07:51 -0700125 mProcessor = new StatsLogProcessor(
126 mUidMap, mPullerManager, mAnomalyAlarmMonitor, mPeriodicAlarmMonitor,
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800127 getElapsedRealtimeNs(),
128 [this](const ConfigKey& key) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800129 shared_ptr<IPendingIntentRef> receiver = mConfigManager->GetConfigReceiver(key);
Jeffrey Huangad213742019-12-16 13:50:06 -0800130 if (receiver == nullptr) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800131 VLOG("Could not find a broadcast receiver for %s", key.ToString().c_str());
Chenjie Yue2219202018-06-08 10:07:51 -0700132 return false;
Jeffrey Huangad213742019-12-16 13:50:06 -0800133 } else if (receiver->sendDataBroadcast(
134 mProcessor->getLastReportTimeNs(key)).isOk()) {
Chenjie Yue2219202018-06-08 10:07:51 -0700135 return true;
Jeffrey Huangad213742019-12-16 13:50:06 -0800136 } else {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800137 VLOG("Failed to send a broadcast for receiver %s", key.ToString().c_str());
Jeffrey Huangad213742019-12-16 13:50:06 -0800138 return false;
Chenjie Yue2219202018-06-08 10:07:51 -0700139 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800140 },
141 [this](const int& uid, const vector<int64_t>& activeConfigs) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800142 shared_ptr<IPendingIntentRef> receiver =
Jeffrey Huang47537a12020-01-06 15:35:34 -0800143 mConfigManager->GetActiveConfigsChangedReceiver(uid);
144 if (receiver == nullptr) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800145 VLOG("Could not find receiver for uid %d", uid);
146 return false;
Jeffrey Huang47537a12020-01-06 15:35:34 -0800147 } else if (receiver->sendActiveConfigsChangedBroadcast(activeConfigs).isOk()) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800148 VLOG("StatsService::active configs broadcast succeeded for uid %d" , uid);
149 return true;
Jeffrey Huang47537a12020-01-06 15:35:34 -0800150 } else {
151 VLOG("StatsService::active configs broadcast failed for uid %d" , uid);
152 return false;
Tej Singh6ede28b2019-01-29 17:06:54 -0800153 }
Chenjie Yue2219202018-06-08 10:07:51 -0700154 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700155
Tej Singh9ec159a2019-11-14 11:59:48 -0800156 mUidMap->setListener(mProcessor);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700157 mConfigManager->AddListener(mProcessor);
158
159 init_system_properties();
Yao Chen0f861862019-03-27 11:51:15 -0700160
161 if (mEventQueue != nullptr) {
162 std::thread pushedEventThread([this] { readLogs(); });
163 pushedEventThread.detach();
164 }
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700165}
166
Yao Chenef99c4f2017-09-22 16:26:54 -0700167StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700168}
169
Yao Chen0f861862019-03-27 11:51:15 -0700170/* Runs on a dedicated thread to process pushed events. */
171void StatsService::readLogs() {
172 // Read forever..... long live statsd
173 while (1) {
174 // Block until an event is available.
175 auto event = mEventQueue->waitPop();
176 // Pass it to StatsLogProcess to all configs/metrics
177 // At this point, the LogEventQueue is not blocked, so that the socketListener
178 // can read events from the socket and write to buffer to avoid data drop.
179 mProcessor->OnLogEvent(event.get());
180 // The ShellSubscriber is only used by shell for local debugging.
181 if (mShellSubscriber != nullptr) {
182 mShellSubscriber->onLogEvent(*event);
183 }
184 }
185}
186
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700187void StatsService::init_system_properties() {
188 mEngBuild = false;
189 const prop_info* buildType = __system_property_find("ro.build.type");
190 if (buildType != NULL) {
191 __system_property_read_callback(buildType, init_build_type_callback, this);
192 }
David Chen0656b7a2017-09-13 15:53:39 -0700193}
194
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700195void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
196 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700197 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700198 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
199 }
200}
201
202/**
Bookatzff71cad2018-09-20 17:17:49 -0700203 * Write data from statsd.
204 * Format for statsdStats: adb shell dumpsys stats --metadata [-v] [--proto]
205 * Format for data report: adb shell dumpsys stats [anything other than --metadata] [--proto]
206 * Anything ending in --proto will be in proto format.
207 * Anything without --metadata as the first argument will be report information.
208 * (bugreports call "adb shell dumpsys stats --dump-priority NORMAL -a --proto")
209 * TODO: Come up with a more robust method of enacting <serviceutils/PriorityDumper.h>.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700210 */
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800211status_t StatsService::dump(int fd, const char** args, uint32_t numArgs) {
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -0800212 if (!checkPermission(kPermissionDump)) {
Tej Singhdd83d702018-04-10 17:24:50 -0700213 return PERMISSION_DENIED;
214 }
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800215
216 int lastArg = numArgs - 1;
Bookatzff71cad2018-09-20 17:17:49 -0700217 bool asProto = false;
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800218 if (lastArg >= 0 && string(args[lastArg]) == "--proto") { // last argument
Bookatzff71cad2018-09-20 17:17:49 -0700219 asProto = true;
220 lastArg--;
Yao Chen884c8c12018-01-26 10:36:25 -0800221 }
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800222 if (numArgs > 0 && string(args[0]) == "--metadata") { // first argument
Bookatzff71cad2018-09-20 17:17:49 -0700223 // Request is to dump statsd stats.
224 bool verbose = false;
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800225 if (lastArg >= 0 && string(args[lastArg]) == "-v") {
Bookatzff71cad2018-09-20 17:17:49 -0700226 verbose = true;
227 lastArg--;
228 }
229 dumpStatsdStats(fd, verbose, asProto);
230 } else {
231 // Request is to dump statsd report data.
232 if (asProto) {
233 dumpIncidentSection(fd);
234 } else {
235 dprintf(fd, "Non-proto format of stats data dump not available; see proto version.\n");
236 }
Tej Singh41b3f9a2018-04-03 17:06:35 -0700237 }
Yao Chen884c8c12018-01-26 10:36:25 -0800238
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700239 return NO_ERROR;
240}
241
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700242/**
Tej Singh41b3f9a2018-04-03 17:06:35 -0700243 * Write debugging data about statsd in text or proto format.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700244 */
Bookatzff71cad2018-09-20 17:17:49 -0700245void StatsService::dumpStatsdStats(int out, bool verbose, bool proto) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700246 if (proto) {
247 vector<uint8_t> data;
248 StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
249 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700250 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700251 }
252 } else {
253 StatsdStats::getInstance().dumpStats(out);
254 mProcessor->dumpStates(out, verbose);
255 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700256}
257
258/**
Bookatzff71cad2018-09-20 17:17:49 -0700259 * Write stats report data in StatsDataDumpProto incident section format.
260 */
261void StatsService::dumpIncidentSection(int out) {
262 ProtoOutputStream proto;
263 for (const ConfigKey& configKey : mConfigManager->GetAllConfigKeys()) {
264 uint64_t reportsListToken =
265 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS_LIST);
Tej Singh61f869e2020-06-12 17:25:17 -0700266 // Don't include the current bucket to avoid skipping buckets.
267 // If we need to include the current bucket later, consider changing to NO_TIME_CONSTRAINTS
268 // or other alternatives to avoid skipping buckets for pulled metrics.
Bookatzff71cad2018-09-20 17:17:49 -0700269 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
Tej Singh61f869e2020-06-12 17:25:17 -0700270 false /* includeCurrentBucket */, false /* erase_data */,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000271 ADB_DUMP,
272 FAST,
273 &proto);
Bookatzff71cad2018-09-20 17:17:49 -0700274 proto.end(reportsListToken);
275 proto.flush(out);
Bookatzc71d9012018-12-19 12:28:38 -0800276 proto.clear();
Bookatzff71cad2018-09-20 17:17:49 -0700277 }
278}
279
280/**
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700281 * Implementation of the adb shell cmd stats command.
282 */
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800283status_t StatsService::handleShellCommand(int in, int out, int err, const char** argv,
284 uint32_t argc) {
285 uid_t uid = AIBinder_getCallingUid();
Stanislav Zholnind7674c22020-02-17 17:48:12 +0000286 if (uid != AID_ROOT && uid != AID_SHELL) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600287 return PERMISSION_DENIED;
288 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700289
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800290 Vector<String8> utf8Args;
291 utf8Args.setCapacity(argc);
292 for (uint32_t i = 0; i < argc; i++) {
293 utf8Args.push(String8(argv[i]));
294 }
295
296 if (argc >= 1) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700297 // adb shell cmd stats config ...
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800298 if (!utf8Args[0].compare(String8("config"))) {
299 return cmd_config(in, out, err, utf8Args);
David Chen0656b7a2017-09-13 15:53:39 -0700300 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700301
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800302 if (!utf8Args[0].compare(String8("print-uid-map"))) {
303 return cmd_print_uid_map(out, utf8Args);
David Chende701692017-10-05 13:16:02 -0700304 }
Yao Chen729093d2017-10-16 10:33:26 -0700305
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800306 if (!utf8Args[0].compare(String8("dump-report"))) {
307 return cmd_dump_report(out, utf8Args);
Yao Chen729093d2017-10-16 10:33:26 -0700308 }
David Chen1481fe12017-10-16 13:16:34 -0700309
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800310 if (!utf8Args[0].compare(String8("pull-source")) && argc > 1) {
311 return cmd_print_pulled_metrics(out, utf8Args);
David Chen1481fe12017-10-16 13:16:34 -0700312 }
David Chenadaf8b32017-11-03 15:42:08 -0700313
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800314 if (!utf8Args[0].compare(String8("send-broadcast"))) {
315 return cmd_trigger_broadcast(out, utf8Args);
David Chen1d7b0cd2017-11-15 14:20:04 -0800316 }
317
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800318 if (!utf8Args[0].compare(String8("print-stats"))) {
319 return cmd_print_stats(out, utf8Args);
David Chenadaf8b32017-11-03 15:42:08 -0700320 }
yro87d983c2017-11-14 21:31:43 -0800321
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800322 if (!utf8Args[0].compare(String8("meminfo"))) {
Yao Chen8d9989b2017-11-18 18:54:50 -0800323 return cmd_dump_memory_info(out);
324 }
yro947fbce2017-11-15 22:50:23 -0800325
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800326 if (!utf8Args[0].compare(String8("write-to-disk"))) {
yro947fbce2017-11-15 22:50:23 -0800327 return cmd_write_data_to_disk(out);
328 }
Bookatzb223c4e2018-02-01 15:35:04 -0800329
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800330 if (!utf8Args[0].compare(String8("log-app-breadcrumb"))) {
331 return cmd_log_app_breadcrumb(out, utf8Args);
Bookatzb223c4e2018-02-01 15:35:04 -0800332 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800333
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800334 if (!utf8Args[0].compare(String8("log-binary-push"))) {
335 return cmd_log_binary_push(out, utf8Args);
Tej Singh53f9dee2019-04-30 17:45:54 -0700336 }
337
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800338 if (!utf8Args[0].compare(String8("clear-puller-cache"))) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800339 return cmd_clear_puller_cache(out);
340 }
Yao Chen876889c2018-05-02 11:16:16 -0700341
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800342 if (!utf8Args[0].compare(String8("print-logs"))) {
343 return cmd_print_logs(out, utf8Args);
Yao Chen876889c2018-05-02 11:16:16 -0700344 }
Ruchir Rastogie92edba2020-04-22 15:37:32 -0700345
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800346 if (!utf8Args[0].compare(String8("send-active-configs"))) {
347 return cmd_trigger_active_config_broadcast(out, utf8Args);
Tej Singh6ede28b2019-01-29 17:06:54 -0800348 }
Ruchir Rastogie92edba2020-04-22 15:37:32 -0700349
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800350 if (!utf8Args[0].compare(String8("data-subscribe"))) {
Tej Singhc9250ce2019-09-20 19:28:53 -0700351 {
352 std::lock_guard<std::mutex> lock(mShellSubscriberMutex);
353 if (mShellSubscriber == nullptr) {
354 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
355 }
Yao Chena80e5c02018-09-04 13:55:29 -0700356 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800357 int timeoutSec = -1;
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800358 if (argc >= 2) {
359 timeoutSec = atoi(utf8Args[1].c_str());
Yao Chen35cb8d62019-01-03 16:49:14 -0800360 }
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800361 mShellSubscriber->startNewSubscription(in, out, timeoutSec);
Yao Chena80e5c02018-09-04 13:55:29 -0700362 return NO_ERROR;
363 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700364 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700365
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700366 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700367 return NO_ERROR;
368}
369
Yao Chena80e5c02018-09-04 13:55:29 -0700370void StatsService::print_cmd_help(int out) {
371 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700372 "usage: adb shell cmd stats print-stats-log [tag_required] "
373 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700374 dprintf(out, "\n");
375 dprintf(out, "\n");
376 dprintf(out, "usage: adb shell cmd stats meminfo\n");
377 dprintf(out, "\n");
378 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
379 dprintf(out, " # adb shell stop\n");
380 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
381 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
382 dprintf(out, " # adb shell start\n");
383 dprintf(out, "\n");
384 dprintf(out, "\n");
385 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
386 dprintf(out, "\n");
387 dprintf(out, " Prints the UID, app name, version mapping.\n");
388 dprintf(out, " PKG Optional package name to print the uids of the package\n");
389 dprintf(out, "\n");
390 dprintf(out, "\n");
Tej Singh3be093b2020-03-04 20:08:38 -0800391 dprintf(out, "usage: adb shell cmd stats pull-source ATOM_TAG [PACKAGE] \n");
Yao Chena80e5c02018-09-04 13:55:29 -0700392 dprintf(out, "\n");
Tej Singh3be093b2020-03-04 20:08:38 -0800393 dprintf(out, " Prints the output of a pulled atom\n");
394 dprintf(out, " UID The atom to pull\n");
395 dprintf(out, " PACKAGE The package to pull from. Default is AID_SYSTEM\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700396 dprintf(out, "\n");
397 dprintf(out, "\n");
398 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
399 dprintf(out, "\n");
400 dprintf(out, " Flushes all data on memory to disk.\n");
401 dprintf(out, "\n");
402 dprintf(out, "\n");
403 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
404 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
405 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
406 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
407 dprintf(out, " uid is used.\n");
408 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
409 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
410 dprintf(out, "\n");
411 dprintf(out, "\n");
Tej Singh53f9dee2019-04-30 17:45:54 -0700412 dprintf(out,
413 "usage: adb shell cmd stats log-binary-push NAME VERSION STAGING ROLLBACK_ENABLED "
414 "LOW_LATENCY STATE EXPERIMENT_IDS\n");
415 dprintf(out, " Log a binary push state changed event.\n");
416 dprintf(out, " NAME The train name.\n");
417 dprintf(out, " VERSION The train version code.\n");
418 dprintf(out, " STAGING If this train requires a restart.\n");
419 dprintf(out, " ROLLBACK_ENABLED If rollback should be enabled for this install.\n");
420 dprintf(out, " LOW_LATENCY If the train requires low latency monitoring.\n");
421 dprintf(out, " STATE The status of the train push.\n");
422 dprintf(out, " Integer value of the enum in atoms.proto.\n");
423 dprintf(out, " EXPERIMENT_IDS Comma separated list of experiment ids.\n");
424 dprintf(out, " Leave blank for none.\n");
425 dprintf(out, "\n");
426 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700427 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
428 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
429 dprintf(out, "\n");
430 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
431 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
432 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
433 dprintf(out, "\n");
434 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
435 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
436 dprintf(out, " uid is used.\n");
437 dprintf(out, " NAME The per-uid name to use\n");
438 dprintf(out, "\n");
439 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
440 dprintf(out, "\n be removed from memory and disk!\n");
441 dprintf(out, "\n");
442 dprintf(out,
Bookatz3e906582018-12-10 17:26:58 -0800443 "usage: adb shell cmd stats dump-report [UID] NAME [--keep_data] "
444 "[--include_current_bucket] [--proto]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700445 dprintf(out, " Dump all metric data for a configuration.\n");
446 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
447 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
448 dprintf(out, " calling uid is used.\n");
449 dprintf(out, " NAME The name of the configuration\n");
Bookatz3e906582018-12-10 17:26:58 -0800450 dprintf(out, " --keep_data Do NOT erase the data upon dumping it.\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700451 dprintf(out, " --proto Print proto binary.\n");
452 dprintf(out, "\n");
453 dprintf(out, "\n");
454 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
455 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
456 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
457 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
458 dprintf(out, " calling uid is used.\n");
459 dprintf(out, " NAME The name of the configuration\n");
460 dprintf(out, "\n");
461 dprintf(out, "\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800462 dprintf(out,
463 "usage: adb shell cmd stats send-active-configs [--uid=UID] [--configs] "
464 "[NAME1] [NAME2] [NAME3..]\n");
465 dprintf(out, " Send a broadcast that informs the subscriber of the current active configs.\n");
466 dprintf(out, " --uid=UID The uid of the configurations. It is only possible to pass\n");
467 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
468 dprintf(out, " calling uid is used.\n");
469 dprintf(out, " --configs Send the list of configs in the name list instead of\n");
470 dprintf(out, " the currently active configs\n");
471 dprintf(out, " NAME LIST List of configuration names to be included in the broadcast.\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800472 dprintf(out, "\n");
473 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700474 dprintf(out, "usage: adb shell cmd stats print-stats\n");
475 dprintf(out, " Prints some basic stats.\n");
476 dprintf(out, " --proto Print proto binary instead of string format.\n");
477 dprintf(out, "\n");
478 dprintf(out, "\n");
479 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
480 dprintf(out, " Clear cached puller data.\n");
481 dprintf(out, "\n");
482 dprintf(out, "usage: adb shell cmd stats print-logs\n");
Ruchir Rastogi432f3702020-07-06 15:48:45 -0700483 dprintf(out, " Requires root privileges.\n");
484 dprintf(out, " Can be disabled by calling adb shell cmd stats print-logs 0\n");
David Chenadaf8b32017-11-03 15:42:08 -0700485}
486
Yao Chena80e5c02018-09-04 13:55:29 -0700487status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800488 string name;
489 bool good = false;
490 int uid;
491 const int argCount = args.size();
492 if (argCount == 2) {
493 // Automatically pick the UID
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800494 uid = AIBinder_getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800495 name.assign(args[1].c_str(), args[1].size());
496 good = true;
497 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800498 good = getUidFromArgs(args, 1, uid);
499 if (!good) {
500 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
501 "other UIDs on eng or userdebug builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800502 }
Bookatzd2386572018-12-14 15:53:14 -0800503 name.assign(args[2].c_str(), args[2].size());
David Chen1d7b0cd2017-11-15 14:20:04 -0800504 }
505 if (!good) {
506 print_cmd_help(out);
507 return UNKNOWN_ERROR;
508 }
David Chend37bc232018-04-12 18:05:11 -0700509 ConfigKey key(uid, StrToInt64(name));
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800510 shared_ptr<IPendingIntentRef> receiver = mConfigManager->GetConfigReceiver(key);
Jeffrey Huangad213742019-12-16 13:50:06 -0800511 if (receiver == nullptr) {
512 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str());
513 return UNKNOWN_ERROR;
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800514 } else if (receiver->sendDataBroadcast(mProcessor->getLastReportTimeNs(key)).isOk()) {
yro74fed972017-11-27 14:42:42 -0800515 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
516 args[2].c_str());
Jeffrey Huangad213742019-12-16 13:50:06 -0800517 } else {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800518 VLOG("StatsService::trigger broadcast failed to %s, %s", args[1].c_str(), args[2].c_str());
Jeffrey Huangad213742019-12-16 13:50:06 -0800519 return UNKNOWN_ERROR;
yro4d889e62017-11-17 15:44:48 -0800520 }
David Chenadaf8b32017-11-03 15:42:08 -0700521 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700522}
523
Tej Singh6ede28b2019-01-29 17:06:54 -0800524status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
525 const int argCount = args.size();
526 int uid;
527 vector<int64_t> configIds;
528 if (argCount == 1) {
529 // Automatically pick the uid and send a broadcast that has no active configs.
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800530 uid = AIBinder_getCallingUid();
Tej Singh6ede28b2019-01-29 17:06:54 -0800531 mProcessor->GetActiveConfigs(uid, configIds);
532 } else {
533 int curArg = 1;
534 if(args[curArg].find("--uid=") == 0) {
535 string uidArgStr(args[curArg].c_str());
536 string uidStr = uidArgStr.substr(6);
537 if (!getUidFromString(uidStr.c_str(), uid)) {
538 dprintf(out, "Invalid UID. Note that the config can only be set for "
539 "other UIDs on eng or userdebug builds.\n");
540 return UNKNOWN_ERROR;
541 }
542 curArg++;
543 } else {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800544 uid = AIBinder_getCallingUid();
Tej Singh6ede28b2019-01-29 17:06:54 -0800545 }
546 if (curArg == argCount || args[curArg] != "--configs") {
547 VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
548 mProcessor->GetActiveConfigs(uid, configIds);
549 } else {
550 // Flag specified, use the given list of configs.
551 curArg++;
552 for (int i = curArg; i < argCount; i++) {
553 char* endp;
554 int64_t configID = strtoll(args[i].c_str(), &endp, 10);
555 if (endp == args[i].c_str() || *endp != '\0') {
556 dprintf(out, "Error parsing config ID.\n");
557 return UNKNOWN_ERROR;
558 }
559 VLOG("Adding config id %ld", static_cast<long>(configID));
560 configIds.push_back(configID);
561 }
562 }
563 }
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800564 shared_ptr<IPendingIntentRef> receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
Jeffrey Huang47537a12020-01-06 15:35:34 -0800565 if (receiver == nullptr) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800566 VLOG("Could not find receiver for uid %d", uid);
Jeffrey Huang47537a12020-01-06 15:35:34 -0800567 return UNKNOWN_ERROR;
568 } else if (receiver->sendActiveConfigsChangedBroadcast(configIds).isOk()) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800569 VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
Jeffrey Huang47537a12020-01-06 15:35:34 -0800570 } else {
571 VLOG("StatsService::trigger active configs changed broadcast failed for uid %d", uid);
572 return UNKNOWN_ERROR;
Tej Singh6ede28b2019-01-29 17:06:54 -0800573 }
574 return NO_ERROR;
575}
576
Yao Chena80e5c02018-09-04 13:55:29 -0700577status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700578 const int argCount = args.size();
579 if (argCount >= 2) {
580 if (args[1] == "update" || args[1] == "remove") {
581 bool good = false;
582 int uid = -1;
583 string name;
584
585 if (argCount == 3) {
586 // Automatically pick the UID
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800587 uid = AIBinder_getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700588 name.assign(args[2].c_str(), args[2].size());
589 good = true;
590 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800591 good = getUidFromArgs(args, 2, uid);
592 if (!good) {
593 dprintf(err, "Invalid UID. Note that the config can only be set for "
594 "other UIDs on eng or userdebug builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700595 }
Bookatzd2386572018-12-14 15:53:14 -0800596 name.assign(args[3].c_str(), args[3].size());
yroe5f82922018-01-22 18:37:27 -0800597 } else if (argCount == 2 && args[1] == "remove") {
598 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700599 }
600
601 if (!good) {
602 // If arg parsing failed, print the help text and return an error.
603 print_cmd_help(out);
604 return UNKNOWN_ERROR;
605 }
606
607 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800608 char* endp;
609 int64_t configID = strtoll(name.c_str(), &endp, 10);
610 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700611 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800612 return UNKNOWN_ERROR;
613 }
614
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700615 // Read stream into buffer.
616 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700617 if (!android::base::ReadFdToString(in, &buffer)) {
618 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700619 return UNKNOWN_ERROR;
620 }
621
622 // Parse buffer.
623 StatsdConfig config;
624 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700625 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700626 return UNKNOWN_ERROR;
627 }
628
629 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800630 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700631 } else {
yro74fed972017-11-27 14:42:42 -0800632 if (argCount == 2) {
633 cmd_remove_all_configs(out);
634 } else {
635 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800636 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800637 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700638 }
639
640 return NO_ERROR;
641 }
David Chen0656b7a2017-09-13 15:53:39 -0700642 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700643 print_cmd_help(out);
644 return UNKNOWN_ERROR;
645}
646
Bookatzff71cad2018-09-20 17:17:49 -0700647status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700648 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800649 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700650 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800651 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700652 bool includeCurrentBucket = false;
Bookatz3e906582018-12-10 17:26:58 -0800653 bool eraseData = true;
Yao Chen729093d2017-10-16 10:33:26 -0700654 int uid;
655 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800656 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
657 proto = true;
658 argCount -= 1;
659 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700660 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
661 includeCurrentBucket = true;
662 argCount -= 1;
663 }
Bookatz3e906582018-12-10 17:26:58 -0800664 if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
665 eraseData = false;
666 argCount -= 1;
667 }
Yao Chen729093d2017-10-16 10:33:26 -0700668 if (argCount == 2) {
669 // Automatically pick the UID
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800670 uid = AIBinder_getCallingUid();
Yao Chen5154a3792017-10-30 22:57:06 -0700671 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700672 good = true;
673 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800674 good = getUidFromArgs(args, 1, uid);
675 if (!good) {
676 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
677 "other UIDs on eng or userdebug builds.\n");
Yao Chen729093d2017-10-16 10:33:26 -0700678 }
Bookatzd2386572018-12-14 15:53:14 -0800679 name.assign(args[2].c_str(), args[2].size());
Yao Chen729093d2017-10-16 10:33:26 -0700680 }
681 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800682 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800683 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000684 includeCurrentBucket, eraseData, ADB_DUMP,
685 NO_TIME_CONSTRAINTS,
686 &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800687 if (proto) {
688 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700689 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800690 }
691 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700692 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800693 }
Yao Chen729093d2017-10-16 10:33:26 -0700694 return android::OK;
695 } else {
696 // If arg parsing failed, print the help text and return an error.
697 print_cmd_help(out);
698 return UNKNOWN_ERROR;
699 }
700 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700701 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700702 return UNKNOWN_ERROR;
703 }
704}
705
Yao Chena80e5c02018-09-04 13:55:29 -0700706status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700707 int argCount = args.size();
708 bool proto = false;
709 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
710 proto = true;
711 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800712 }
Yao Chenb3561512017-11-21 18:07:17 -0800713 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700714 if (proto) {
715 vector<uint8_t> data;
716 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
717 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700718 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700719 }
720
721 } else {
722 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
723 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700724 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700725 mProcessor->GetMetricsSize(key));
726 }
727 statsdStats.dumpStats(out);
728 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800729 return NO_ERROR;
730}
731
Yao Chena80e5c02018-09-04 13:55:29 -0700732status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800733 if (args.size() > 1) {
734 string pkg;
735 pkg.assign(args[1].c_str(), args[1].size());
736 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700737 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800738 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700739 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800740 }
Yao Chena80e5c02018-09-04 13:55:29 -0700741 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800742 } else {
743 mUidMap->printUidMap(out);
744 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700745 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700746}
747
Yao Chena80e5c02018-09-04 13:55:29 -0700748status_t StatsService::cmd_write_data_to_disk(int out) {
749 dprintf(out, "Writing data to disk\n");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000750 mProcessor->WriteDataToDisk(ADB_DUMP, NO_TIME_CONSTRAINTS);
yro947fbce2017-11-15 22:50:23 -0800751 return NO_ERROR;
752}
753
Yao Chena80e5c02018-09-04 13:55:29 -0700754status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800755 bool good = false;
756 int32_t uid;
757 int32_t label;
758 int32_t state;
759 const int argCount = args.size();
760 if (argCount == 3) {
761 // Automatically pick the UID
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800762 uid = AIBinder_getCallingUid();
Bookatzb223c4e2018-02-01 15:35:04 -0800763 label = atoi(args[1].c_str());
764 state = atoi(args[2].c_str());
765 good = true;
766 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800767 good = getUidFromArgs(args, 1, uid);
768 if (!good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700769 dprintf(out,
Bookatzd2386572018-12-14 15:53:14 -0800770 "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
771 "done for other UIDs on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800772 }
Bookatzd2386572018-12-14 15:53:14 -0800773 label = atoi(args[2].c_str());
774 state = atoi(args[3].c_str());
Bookatzb223c4e2018-02-01 15:35:04 -0800775 }
776 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700777 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800778 android::os::statsd::util::stats_write(
779 android::os::statsd::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800780 } else {
781 print_cmd_help(out);
782 return UNKNOWN_ERROR;
783 }
784 return NO_ERROR;
785}
786
Tej Singh53f9dee2019-04-30 17:45:54 -0700787status_t StatsService::cmd_log_binary_push(int out, const Vector<String8>& args) {
788 // Security checks are done in the sendBinaryPushStateChanged atom.
789 const int argCount = args.size();
790 if (argCount != 7 && argCount != 8) {
791 dprintf(out, "Incorrect number of argument supplied\n");
792 return UNKNOWN_ERROR;
793 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800794 string trainName = string(args[1].c_str());
Tej Singh53f9dee2019-04-30 17:45:54 -0700795 int64_t trainVersion = strtoll(args[2].c_str(), nullptr, 10);
Tej Singh53f9dee2019-04-30 17:45:54 -0700796 int32_t state = atoi(args[6].c_str());
797 vector<int64_t> experimentIds;
798 if (argCount == 8) {
799 vector<string> experimentIdsString = android::base::Split(string(args[7].c_str()), ",");
800 for (string experimentIdString : experimentIdsString) {
801 int64_t experimentId = strtoll(experimentIdString.c_str(), nullptr, 10);
802 experimentIds.push_back(experimentId);
803 }
804 }
805 dprintf(out, "Logging BinaryPushStateChanged\n");
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800806 vector<uint8_t> experimentIdBytes;
807 writeExperimentIdsToProto(experimentIds, &experimentIdBytes);
808 LogEvent event(trainName, trainVersion, args[3], args[4], args[5], state, experimentIdBytes, 0);
809 mProcessor->OnLogEvent(&event);
Tej Singh53f9dee2019-04-30 17:45:54 -0700810 return NO_ERROR;
811}
812
Yao Chena80e5c02018-09-04 13:55:29 -0700813status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700814 int s = atoi(args[1].c_str());
Tej Singh3be093b2020-03-04 20:08:38 -0800815 vector<int32_t> uids;
816 if (args.size() > 2) {
817 string package = string(args[2].c_str());
818 auto it = UidMap::sAidToUidMapping.find(package);
819 if (it != UidMap::sAidToUidMapping.end()) {
820 uids.push_back(it->second);
821 } else {
822 set<int32_t> uids_set = mUidMap->getAppUid(package);
823 uids.insert(uids.end(), uids_set.begin(), uids_set.end());
824 }
825 } else {
826 uids.push_back(AID_SYSTEM);
827 }
828 vector<shared_ptr<LogEvent>> stats;
Tej Singh7b975a82020-05-11 11:05:08 -0700829 if (mPullerManager->Pull(s, uids, getElapsedRealtimeNs(), &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700830 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700831 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700832 }
Yao Chena80e5c02018-09-04 13:55:29 -0700833 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700834 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700835 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700836 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700837}
838
Yao Chena80e5c02018-09-04 13:55:29 -0700839status_t StatsService::cmd_remove_all_configs(int out) {
840 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800841 VLOG("StatsService::cmd_remove_all_configs was called");
842 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800843 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800844 return NO_ERROR;
845}
846
Yao Chena80e5c02018-09-04 13:55:29 -0700847status_t StatsService::cmd_dump_memory_info(int out) {
848 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800849 return NO_ERROR;
850}
851
Yao Chena80e5c02018-09-04 13:55:29 -0700852status_t StatsService::cmd_clear_puller_cache(int out) {
Yangster-mac932ecec2018-02-01 10:23:52 -0800853 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800854 AIBinder_getCallingPid(), AIBinder_getCallingUid());
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -0800855 if (checkPermission(kPermissionDump)) {
Chenjie Yue2219202018-06-08 10:07:51 -0700856 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700857 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800858 return NO_ERROR;
859 } else {
860 return PERMISSION_DENIED;
861 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800862}
863
Yao Chena80e5c02018-09-04 13:55:29 -0700864status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Ruchir Rastogi432f3702020-07-06 15:48:45 -0700865 Status status = checkUid(AID_ROOT);
866 if (!status.isOk()) {
Yao Chen876889c2018-05-02 11:16:16 -0700867 return PERMISSION_DENIED;
868 }
Ruchir Rastogi432f3702020-07-06 15:48:45 -0700869
870 VLOG("StatsService::cmd_print_logs with pid %i, uid %i", AIBinder_getCallingPid(),
871 AIBinder_getCallingUid());
872 bool enabled = true;
873 if (args.size() >= 2) {
874 enabled = atoi(args[1].c_str()) != 0;
875 }
876 mProcessor->setPrintLogs(enabled);
877 return NO_ERROR;
Yao Chen876889c2018-05-02 11:16:16 -0700878}
879
Bookatzd2386572018-12-14 15:53:14 -0800880bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800881 return getUidFromString(args[uidArgIndex].c_str(), uid);
882}
883
884bool StatsService::getUidFromString(const char* s, int32_t& uid) {
Bookatzd2386572018-12-14 15:53:14 -0800885 if (*s == '\0') {
886 return false;
887 }
888 char* endc = NULL;
889 int64_t longUid = strtol(s, &endc, 0);
890 if (*endc != '\0') {
891 return false;
892 }
893 int32_t goodUid = static_cast<int32_t>(longUid);
894 if (longUid < 0 || static_cast<uint64_t>(longUid) != static_cast<uid_t>(goodUid)) {
895 return false; // It was not of uid_t type.
896 }
897 uid = goodUid;
898
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800899 int32_t callingUid = AIBinder_getCallingUid();
Bookatzd2386572018-12-14 15:53:14 -0800900 return mEngBuild // UserDebug/EngBuild are allowed to impersonate uids.
901 || (callingUid == goodUid) // Anyone can 'impersonate' themselves.
902 || (callingUid == AID_ROOT && goodUid == AID_SHELL); // ROOT can impersonate SHELL.
903}
904
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800905Status StatsService::informAllUidData(const ScopedFileDescriptor& fd) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600906 ENFORCE_UID(AID_SYSTEM);
Max Dashouk11e0d402019-05-16 16:58:07 -0700907 // Read stream into buffer.
908 string buffer;
909 if (!android::base::ReadFdToString(fd.get(), &buffer)) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800910 return exception(EX_ILLEGAL_ARGUMENT, "Failed to read all data from the pipe.");
Max Dashouk11e0d402019-05-16 16:58:07 -0700911 }
Jeff Sharkey6b649252018-04-16 09:50:22 -0600912
Max Dashouk11e0d402019-05-16 16:58:07 -0700913 // Parse buffer.
914 UidData uidData;
915 if (!uidData.ParseFromString(buffer)) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800916 return exception(EX_ILLEGAL_ARGUMENT, "Error parsing proto stream for UidData.");
Max Dashouk11e0d402019-05-16 16:58:07 -0700917 }
David Chende701692017-10-05 13:16:02 -0700918
Max Dashouk11e0d402019-05-16 16:58:07 -0700919 vector<String16> versionStrings;
920 vector<String16> installers;
921 vector<String16> packageNames;
922 vector<int32_t> uids;
923 vector<int64_t> versions;
924
925 const auto numEntries = uidData.app_info_size();
926 versionStrings.reserve(numEntries);
927 installers.reserve(numEntries);
928 packageNames.reserve(numEntries);
929 uids.reserve(numEntries);
930 versions.reserve(numEntries);
931
932 for (const auto& appInfo: uidData.app_info()) {
933 packageNames.emplace_back(String16(appInfo.package_name().c_str()));
934 uids.push_back(appInfo.uid());
935 versions.push_back(appInfo.version());
936 versionStrings.emplace_back(String16(appInfo.version_string().c_str()));
937 installers.emplace_back(String16(appInfo.installer().c_str()));
938 }
939
940 mUidMap->updateMap(getElapsedRealtimeNs(),
941 uids,
942 versions,
943 versionStrings,
944 packageNames,
945 installers);
946
Tej Singhe678cb72020-04-14 16:23:30 -0700947 mBootCompleteTrigger.markComplete(kUidMapReceivedTag);
Max Dashouk11e0d402019-05-16 16:58:07 -0700948 VLOG("StatsService::informAllUidData UidData proto parsed successfully.");
David Chende701692017-10-05 13:16:02 -0700949 return Status::ok();
950}
951
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800952Status StatsService::informOnePackage(const string& app, int32_t uid, int64_t version,
953 const string& versionString, const string& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600954 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700955
Jeff Sharkey6b649252018-04-16 09:50:22 -0600956 VLOG("StatsService::informOnePackage was called");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800957 String16 utf16App = String16(app.c_str());
958 String16 utf16VersionString = String16(versionString.c_str());
959 String16 utf16Installer = String16(installer.c_str());
960
961 mUidMap->updateApp(getElapsedRealtimeNs(), utf16App, uid, version, utf16VersionString,
962 utf16Installer);
David Chende701692017-10-05 13:16:02 -0700963 return Status::ok();
964}
965
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800966Status StatsService::informOnePackageRemoved(const string& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600967 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700968
Jeff Sharkey6b649252018-04-16 09:50:22 -0600969 VLOG("StatsService::informOnePackageRemoved was called");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800970 String16 utf16App = String16(app.c_str());
971 mUidMap->removeApp(getElapsedRealtimeNs(), utf16App, uid);
yro01924022018-02-20 18:20:49 -0800972 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -0700973 return Status::ok();
974}
975
Yangster-mac932ecec2018-02-01 10:23:52 -0800976Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600977 ENFORCE_UID(AID_SYSTEM);
978
Yangster-mac932ecec2018-02-01 10:23:52 -0800979 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700980 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800981 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
982 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
983 if (alarmSet.size() > 0) {
984 VLOG("Found periodic alarm fired.");
985 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
986 } else {
987 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
988 }
989 return Status::ok();
990}
991
Yao Chenef99c4f2017-09-22 16:26:54 -0700992Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600993 ENFORCE_UID(AID_SYSTEM);
994
yro74fed972017-11-27 14:42:42 -0800995 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700996 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -0800997 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700998 return Status::ok();
999}
1000
Yao Chenef99c4f2017-09-22 16:26:54 -07001001Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001002 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001003
1004 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -08001005 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -07001006 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001007 return Status::ok();
1008}
1009
Yangster-mac892f3d32018-05-02 14:16:48 -07001010Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001011 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -07001012 VLOG("StatsService::informDeviceShutdown");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001013 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001014 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
Jeffrey Huangb8f54032020-03-23 13:42:42 -07001015 mProcessor->SaveMetadataToDisk(getWallClockNs(), getElapsedRealtimeNs());
yro947fbce2017-11-15 22:50:23 -08001016 return Status::ok();
1017}
1018
Yao Chenef99c4f2017-09-22 16:26:54 -07001019void StatsService::sayHiToStatsCompanion() {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001020 shared_ptr<IStatsCompanionService> statsCompanion = getStatsCompanionService();
Bookatzb487b552017-09-18 11:26:01 -07001021 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -08001022 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -07001023 statsCompanion->statsdReady();
1024 } else {
yro74fed972017-11-27 14:42:42 -08001025 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -07001026 }
1027}
1028
Yao Chenef99c4f2017-09-22 16:26:54 -07001029Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001030 ENFORCE_UID(AID_SYSTEM);
1031
yro74fed972017-11-27 14:42:42 -08001032 VLOG("StatsService::statsCompanionReady was called");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001033 shared_ptr<IStatsCompanionService> statsCompanion = getStatsCompanionService();
Bookatzb487b552017-09-18 11:26:01 -07001034 if (statsCompanion == nullptr) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001035 return exception(EX_NULL_POINTER,
1036 "StatsCompanion unavailable despite it contacting statsd.");
Bookatzb487b552017-09-18 11:26:01 -07001037 }
yro74fed972017-11-27 14:42:42 -08001038 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001039 AIBinder_linkToDeath(statsCompanion->asBinder().get(),
1040 mStatsCompanionServiceDeathRecipient.get(), this);
Chenjie Yue2219202018-06-08 10:07:51 -07001041 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -08001042 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
1043 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -07001044 return Status::ok();
1045}
1046
Jeffrey Huangd8f53302020-04-06 18:09:55 -07001047Status StatsService::bootCompleted() {
1048 ENFORCE_UID(AID_SYSTEM);
1049
1050 VLOG("StatsService::bootCompleted was called");
Tej Singhe678cb72020-04-14 16:23:30 -07001051 mBootCompleteTrigger.markComplete(kBootCompleteTag);
Jeffrey Huangd8f53302020-04-06 18:09:55 -07001052 return Status::ok();
1053}
1054
Joe Onorato9fc9edf2017-10-15 20:08:52 -07001055void StatsService::Startup() {
1056 mConfigManager->Startup();
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001057 mProcessor->LoadActiveConfigsFromDisk();
Jeffrey Huang475677e2020-03-30 19:52:07 -07001058 mProcessor->LoadMetadataFromDisk(getWallClockNs(), getElapsedRealtimeNs());
Bookatz906a35c2017-09-20 15:26:44 -07001059}
1060
Yangster-mac97e7d202018-10-09 11:05:39 -07001061void StatsService::Terminate() {
1062 ALOGI("StatsService::Terminating");
1063 if (mProcessor != nullptr) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001064 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001065 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
Jeffrey Huangb8f54032020-03-23 13:42:42 -07001066 mProcessor->SaveMetadataToDisk(getWallClockNs(), getElapsedRealtimeNs());
Yangster-mac97e7d202018-10-09 11:05:39 -07001067 }
1068}
1069
Yao Chen0f861862019-03-27 11:51:15 -07001070// Test only interface!!!
Yao Chen3ff3a492018-08-06 16:17:37 -07001071void StatsService::OnLogEvent(LogEvent* event) {
1072 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -07001073 if (mShellSubscriber != nullptr) {
1074 mShellSubscriber->onLogEvent(*event);
1075 }
Bookatz906a35c2017-09-20 15:26:44 -07001076}
1077
Jooyung Han592d6bf2020-02-22 00:46:52 +09001078Status StatsService::getData(int64_t key, const int32_t callingUid, vector<uint8_t>* output) {
Jeffrey Huang04f948b2020-01-07 10:05:25 -08001079 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001080
Jeffrey Huang04f948b2020-01-07 10:05:25 -08001081 VLOG("StatsService::getData with Uid %i", callingUid);
1082 ConfigKey configKey(callingUid, key);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001083 // The dump latency does not matter here since we do not include the current bucket, we do not
1084 // need to pull any new data anyhow.
David Chen56ae0d92018-05-11 16:00:22 -07001085 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
Jooyung Han592d6bf2020-02-22 00:46:52 +09001086 true /* erase_data */, GET_DATA_CALLED, FAST, output);
Bookatz4f716292018-04-10 17:15:12 -07001087 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001088}
1089
Jooyung Han592d6bf2020-02-22 00:46:52 +09001090Status StatsService::getMetadata(vector<uint8_t>* output) {
Jeffrey Huang9613a972020-01-07 10:05:03 -08001091 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001092
Jooyung Han592d6bf2020-02-22 00:46:52 +09001093 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
Bookatz4f716292018-04-10 17:15:12 -07001094 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -08001095}
1096
Jooyung Han592d6bf2020-02-22 00:46:52 +09001097Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001098 const int32_t callingUid) {
1099 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001100
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001101 if (addConfigurationChecked(callingUid, key, config)) {
David Chen661f7912018-01-22 17:46:24 -08001102 return Status::ok();
1103 } else {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001104 return exception(EX_ILLEGAL_ARGUMENT, "Could not parse malformatted StatsdConfig.");
David Chen661f7912018-01-22 17:46:24 -08001105 }
1106}
1107
Jooyung Han592d6bf2020-02-22 00:46:52 +09001108bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
David Chen9fdd4032018-03-20 14:38:56 -07001109 ConfigKey configKey(uid, key);
1110 StatsdConfig cfg;
1111 if (config.size() > 0) { // If the config is empty, skip parsing.
1112 if (!cfg.ParseFromArray(&config[0], config.size())) {
1113 return false;
1114 }
1115 }
1116 mConfigManager->UpdateConfig(configKey, cfg);
1117 return true;
1118}
1119
Jeffrey Huangad213742019-12-16 13:50:06 -08001120Status StatsService::removeDataFetchOperation(int64_t key,
1121 const int32_t callingUid) {
1122 ENFORCE_UID(AID_SYSTEM);
1123 ConfigKey configKey(callingUid, key);
Bookatz4f716292018-04-10 17:15:12 -07001124 mConfigManager->RemoveConfigReceiver(configKey);
1125 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -08001126}
1127
Jeff Sharkey6b649252018-04-16 09:50:22 -06001128Status StatsService::setDataFetchOperation(int64_t key,
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001129 const shared_ptr<IPendingIntentRef>& pir,
Jeffrey Huangad213742019-12-16 13:50:06 -08001130 const int32_t callingUid) {
1131 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001132
Jeffrey Huangad213742019-12-16 13:50:06 -08001133 ConfigKey configKey(callingUid, key);
1134 mConfigManager->SetConfigReceiver(configKey, pir);
David Chen48944902018-05-03 10:29:11 -07001135 if (StorageManager::hasConfigMetricsReport(configKey)) {
1136 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
1137 configKey.ToString().c_str());
1138 mProcessor->noteOnDiskData(configKey);
1139 }
Bookatz4f716292018-04-10 17:15:12 -07001140 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001141}
1142
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001143Status StatsService::setActiveConfigsChangedOperation(const shared_ptr<IPendingIntentRef>& pir,
Jeffrey Huang47537a12020-01-06 15:35:34 -08001144 const int32_t callingUid,
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001145 vector<int64_t>* output) {
Jeffrey Huang47537a12020-01-06 15:35:34 -08001146 ENFORCE_UID(AID_SYSTEM);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001147
Jeffrey Huang47537a12020-01-06 15:35:34 -08001148 mConfigManager->SetActiveConfigsChangedReceiver(callingUid, pir);
Tej Singh6ede28b2019-01-29 17:06:54 -08001149 if (output != nullptr) {
Jeffrey Huang47537a12020-01-06 15:35:34 -08001150 mProcessor->GetActiveConfigs(callingUid, *output);
Tej Singh6ede28b2019-01-29 17:06:54 -08001151 } else {
1152 ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
1153 }
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001154 return Status::ok();
1155}
1156
Jeffrey Huang47537a12020-01-06 15:35:34 -08001157Status StatsService::removeActiveConfigsChangedOperation(const int32_t callingUid) {
1158 ENFORCE_UID(AID_SYSTEM);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001159
Jeffrey Huang47537a12020-01-06 15:35:34 -08001160 mConfigManager->RemoveActiveConfigsChangedReceiver(callingUid);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001161 return Status::ok();
1162}
1163
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001164Status StatsService::removeConfiguration(int64_t key, const int32_t callingUid) {
1165 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001166
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001167 ConfigKey configKey(callingUid, key);
Bookatz4f716292018-04-10 17:15:12 -07001168 mConfigManager->RemoveConfig(configKey);
Bookatz4f716292018-04-10 17:15:12 -07001169 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001170}
1171
Bookatzc6977972018-01-16 16:55:05 -08001172Status StatsService::setBroadcastSubscriber(int64_t configId,
1173 int64_t subscriberId,
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001174 const shared_ptr<IPendingIntentRef>& pir,
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001175 const int32_t callingUid) {
1176 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001177
Bookatzc6977972018-01-16 16:55:05 -08001178 VLOG("StatsService::setBroadcastSubscriber called.");
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001179 ConfigKey configKey(callingUid, configId);
Bookatz4f716292018-04-10 17:15:12 -07001180 SubscriberReporter::getInstance()
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001181 .setBroadcastSubscriber(configKey, subscriberId, pir);
Bookatz4f716292018-04-10 17:15:12 -07001182 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001183}
1184
1185Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001186 int64_t subscriberId,
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001187 const int32_t callingUid) {
1188 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001189
Bookatzc6977972018-01-16 16:55:05 -08001190 VLOG("StatsService::unsetBroadcastSubscriber called.");
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001191 ConfigKey configKey(callingUid, configId);
Bookatz4f716292018-04-10 17:15:12 -07001192 SubscriberReporter::getInstance()
1193 .unsetBroadcastSubscriber(configKey, subscriberId);
1194 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001195}
1196
Jeffrey Huangd7fda532020-04-06 18:19:46 -07001197Status StatsService::allPullersFromBootRegistered() {
1198 ENFORCE_UID(AID_SYSTEM);
1199
1200 VLOG("StatsService::allPullersFromBootRegistered was called");
Tej Singhe678cb72020-04-14 16:23:30 -07001201 mBootCompleteTrigger.markComplete(kAllPullersRegisteredTag);
Jeffrey Huangd7fda532020-04-06 18:19:46 -07001202 return Status::ok();
1203}
1204
Tej Singh72a70a82020-02-26 23:46:29 -08001205Status StatsService::registerPullAtomCallback(int32_t uid, int32_t atomTag, int64_t coolDownMillis,
1206 int64_t timeoutMillis,
1207 const std::vector<int32_t>& additiveFields,
1208 const shared_ptr<IPullAtomCallback>& pullerCallback) {
Tej Singh6a5c9432019-10-11 11:07:06 -07001209 ENFORCE_UID(AID_SYSTEM);
Tej Singhb7802512019-12-04 17:57:04 -08001210 VLOG("StatsService::registerPullAtomCallback called.");
Tej Singh72a70a82020-02-26 23:46:29 -08001211 mPullerManager->RegisterPullAtomCallback(uid, atomTag, MillisToNano(coolDownMillis),
1212 MillisToNano(timeoutMillis), additiveFields,
Tej Singhb7802512019-12-04 17:57:04 -08001213 pullerCallback);
1214 return Status::ok();
1215}
1216
Tej Singh73597dc2020-03-13 18:42:40 -07001217Status StatsService::registerNativePullAtomCallback(
1218 int32_t atomTag, int64_t coolDownMillis, int64_t timeoutMillis,
1219 const std::vector<int32_t>& additiveFields,
1220 const shared_ptr<IPullAtomCallback>& pullerCallback) {
Tej Singh10458ec2020-03-17 11:04:02 -07001221 if (!checkPermission(kPermissionRegisterPullAtom)) {
1222 return exception(
1223 EX_SECURITY,
1224 StringPrintf("Uid %d does not have the %s permission when registering atom %d",
1225 AIBinder_getCallingUid(), kPermissionRegisterPullAtom, atomTag));
1226 }
Tej Singhb7802512019-12-04 17:57:04 -08001227 VLOG("StatsService::registerNativePullAtomCallback called.");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001228 int32_t uid = AIBinder_getCallingUid();
Tej Singh73597dc2020-03-13 18:42:40 -07001229 mPullerManager->RegisterPullAtomCallback(uid, atomTag, MillisToNano(coolDownMillis),
1230 MillisToNano(timeoutMillis), additiveFields,
Tej Singh6a5c9432019-10-11 11:07:06 -07001231 pullerCallback);
Tej Singh59184292019-10-11 11:07:06 -07001232 return Status::ok();
1233}
1234
Tej Singhfa1c1372019-12-05 20:36:54 -08001235Status StatsService::unregisterPullAtomCallback(int32_t uid, int32_t atomTag) {
1236 ENFORCE_UID(AID_SYSTEM);
1237 VLOG("StatsService::unregisterPullAtomCallback called.");
1238 mPullerManager->UnregisterPullAtomCallback(uid, atomTag);
1239 return Status::ok();
1240}
1241
Tej Singh8f358602020-01-15 16:05:39 -08001242Status StatsService::unregisterNativePullAtomCallback(int32_t atomTag) {
Tej Singh10458ec2020-03-17 11:04:02 -07001243 if (!checkPermission(kPermissionRegisterPullAtom)) {
1244 return exception(
1245 EX_SECURITY,
1246 StringPrintf("Uid %d does not have the %s permission when unregistering atom %d",
1247 AIBinder_getCallingUid(), kPermissionRegisterPullAtom, atomTag));
1248 }
Tej Singh8f358602020-01-15 16:05:39 -08001249 VLOG("StatsService::unregisterNativePullAtomCallback called.");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001250 int32_t uid = AIBinder_getCallingUid();
Tej Singh8f358602020-01-15 16:05:39 -08001251 mPullerManager->UnregisterPullAtomCallback(uid, atomTag);
1252 return Status::ok();
1253}
1254
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001255Status StatsService::getRegisteredExperimentIds(std::vector<int64_t>* experimentIdsOut) {
Jeffrey Huang80c9a972020-01-07 10:04:27 -08001256 ENFORCE_UID(AID_SYSTEM);
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001257 // TODO: add verifier permission
1258
Jonathan Nguyen703c42f2020-02-04 15:54:26 -08001259 experimentIdsOut->clear();
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001260 // Read the latest train info
Jonathan Nguyen703c42f2020-02-04 15:54:26 -08001261 vector<InstallTrainInfo> trainInfoList = StorageManager::readAllTrainInfo();
1262 if (trainInfoList.empty()) {
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001263 // No train info means no experiment IDs, return an empty list
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001264 return Status::ok();
1265 }
1266
1267 // Copy the experiment IDs to the out vector
Jonathan Nguyen703c42f2020-02-04 15:54:26 -08001268 for (InstallTrainInfo& trainInfo : trainInfoList) {
1269 experimentIdsOut->insert(experimentIdsOut->end(),
1270 trainInfo.experimentIds.begin(),
1271 trainInfo.experimentIds.end());
1272 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001273 return Status::ok();
1274}
1275
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001276void StatsService::statsCompanionServiceDied(void* cookie) {
1277 auto thiz = static_cast<StatsService*>(cookie);
1278 thiz->statsCompanionServiceDiedImpl();
1279}
1280
1281void StatsService::statsCompanionServiceDiedImpl() {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001282 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001283 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1284 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001285 ALOGW("Reset statsd upon system server restarts.");
Tej Singhf53d4452019-05-09 18:17:59 -07001286 int64_t systemServerRestartNs = getElapsedRealtimeNs();
Jeffrey Huangb8f54032020-03-23 13:42:42 -07001287 ProtoOutputStream activeConfigsProto;
Tej Singhf53d4452019-05-09 18:17:59 -07001288 mProcessor->WriteActiveConfigsToProtoOutputStream(systemServerRestartNs,
Jeffrey Huangb8f54032020-03-23 13:42:42 -07001289 STATSCOMPANION_DIED, &activeConfigsProto);
1290 metadata::StatsMetadataList metadataList;
1291 mProcessor->WriteMetadataToProto(getWallClockNs(),
1292 systemServerRestartNs, &metadataList);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001293 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED, FAST);
Yangster-mac892f3d32018-05-02 14:16:48 -07001294 mProcessor->resetConfigs();
Tej Singhf53d4452019-05-09 18:17:59 -07001295
1296 std::string serializedActiveConfigs;
Jeffrey Huangb8f54032020-03-23 13:42:42 -07001297 if (activeConfigsProto.serializeToString(&serializedActiveConfigs)) {
Tej Singhf53d4452019-05-09 18:17:59 -07001298 ActiveConfigList activeConfigs;
1299 if (activeConfigs.ParseFromString(serializedActiveConfigs)) {
1300 mProcessor->SetConfigsActiveState(activeConfigs, systemServerRestartNs);
1301 }
1302 }
Jeffrey Huang475677e2020-03-30 19:52:07 -07001303 mProcessor->SetMetadataState(metadataList, getWallClockNs(), systemServerRestartNs);
Yangster-mac892f3d32018-05-02 14:16:48 -07001304 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001305 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1306 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001307 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001308}
1309
Yao Chenef99c4f2017-09-22 16:26:54 -07001310} // namespace statsd
1311} // namespace os
1312} // namespace android