blob: 03955bcb89f897aa9a78fa24f6db6242c24e33ff [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),
121 mStatsCompanionServiceDeathRecipient(AIBinder_DeathRecipient_new(
122 StatsService::statsCompanionServiceDied)) {
Yao Chen4ce07292019-02-13 13:06:36 -0800123 mUidMap = UidMap::getInstance();
Chenjie Yue2219202018-06-08 10:07:51 -0700124 mPullerManager = new StatsPullerManager();
Chenjie Yu80f91122018-01-31 20:24:50 -0800125 StatsPuller::SetUidMap(mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700126 mConfigManager = new ConfigManager();
Chenjie Yue2219202018-06-08 10:07:51 -0700127 mProcessor = new StatsLogProcessor(
128 mUidMap, mPullerManager, mAnomalyAlarmMonitor, mPeriodicAlarmMonitor,
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800129 getElapsedRealtimeNs(),
130 [this](const ConfigKey& key) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800131 shared_ptr<IPendingIntentRef> receiver = mConfigManager->GetConfigReceiver(key);
Jeffrey Huangad213742019-12-16 13:50:06 -0800132 if (receiver == nullptr) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800133 VLOG("Could not find a broadcast receiver for %s", key.ToString().c_str());
Chenjie Yue2219202018-06-08 10:07:51 -0700134 return false;
Jeffrey Huangad213742019-12-16 13:50:06 -0800135 } else if (receiver->sendDataBroadcast(
136 mProcessor->getLastReportTimeNs(key)).isOk()) {
Chenjie Yue2219202018-06-08 10:07:51 -0700137 return true;
Jeffrey Huangad213742019-12-16 13:50:06 -0800138 } else {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800139 VLOG("Failed to send a broadcast for receiver %s", key.ToString().c_str());
Jeffrey Huangad213742019-12-16 13:50:06 -0800140 return false;
Chenjie Yue2219202018-06-08 10:07:51 -0700141 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800142 },
143 [this](const int& uid, const vector<int64_t>& activeConfigs) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800144 shared_ptr<IPendingIntentRef> receiver =
Jeffrey Huang47537a12020-01-06 15:35:34 -0800145 mConfigManager->GetActiveConfigsChangedReceiver(uid);
146 if (receiver == nullptr) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800147 VLOG("Could not find receiver for uid %d", uid);
148 return false;
Jeffrey Huang47537a12020-01-06 15:35:34 -0800149 } else if (receiver->sendActiveConfigsChangedBroadcast(activeConfigs).isOk()) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800150 VLOG("StatsService::active configs broadcast succeeded for uid %d" , uid);
151 return true;
Jeffrey Huang47537a12020-01-06 15:35:34 -0800152 } else {
153 VLOG("StatsService::active configs broadcast failed for uid %d" , uid);
154 return false;
Tej Singh6ede28b2019-01-29 17:06:54 -0800155 }
Chenjie Yue2219202018-06-08 10:07:51 -0700156 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700157
Tej Singh9ec159a2019-11-14 11:59:48 -0800158 mUidMap->setListener(mProcessor);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700159 mConfigManager->AddListener(mProcessor);
160
161 init_system_properties();
Yao Chen0f861862019-03-27 11:51:15 -0700162
163 if (mEventQueue != nullptr) {
164 std::thread pushedEventThread([this] { readLogs(); });
165 pushedEventThread.detach();
166 }
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700167}
168
Yao Chenef99c4f2017-09-22 16:26:54 -0700169StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700170}
171
Yao Chen0f861862019-03-27 11:51:15 -0700172/* Runs on a dedicated thread to process pushed events. */
173void StatsService::readLogs() {
174 // Read forever..... long live statsd
175 while (1) {
176 // Block until an event is available.
177 auto event = mEventQueue->waitPop();
178 // Pass it to StatsLogProcess to all configs/metrics
179 // At this point, the LogEventQueue is not blocked, so that the socketListener
180 // can read events from the socket and write to buffer to avoid data drop.
181 mProcessor->OnLogEvent(event.get());
182 // The ShellSubscriber is only used by shell for local debugging.
183 if (mShellSubscriber != nullptr) {
184 mShellSubscriber->onLogEvent(*event);
185 }
186 }
187}
188
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700189void StatsService::init_system_properties() {
190 mEngBuild = false;
191 const prop_info* buildType = __system_property_find("ro.build.type");
192 if (buildType != NULL) {
193 __system_property_read_callback(buildType, init_build_type_callback, this);
194 }
David Chen0656b7a2017-09-13 15:53:39 -0700195}
196
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700197void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
198 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700199 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700200 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
201 }
202}
203
204/**
Bookatzff71cad2018-09-20 17:17:49 -0700205 * Write data from statsd.
206 * Format for statsdStats: adb shell dumpsys stats --metadata [-v] [--proto]
207 * Format for data report: adb shell dumpsys stats [anything other than --metadata] [--proto]
208 * Anything ending in --proto will be in proto format.
209 * Anything without --metadata as the first argument will be report information.
210 * (bugreports call "adb shell dumpsys stats --dump-priority NORMAL -a --proto")
211 * TODO: Come up with a more robust method of enacting <serviceutils/PriorityDumper.h>.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700212 */
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800213status_t StatsService::dump(int fd, const char** args, uint32_t numArgs) {
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -0800214 if (!checkPermission(kPermissionDump)) {
Tej Singhdd83d702018-04-10 17:24:50 -0700215 return PERMISSION_DENIED;
216 }
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800217
218 int lastArg = numArgs - 1;
Bookatzff71cad2018-09-20 17:17:49 -0700219 bool asProto = false;
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800220 if (lastArg >= 0 && string(args[lastArg]) == "--proto") { // last argument
Bookatzff71cad2018-09-20 17:17:49 -0700221 asProto = true;
222 lastArg--;
Yao Chen884c8c12018-01-26 10:36:25 -0800223 }
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800224 if (numArgs > 0 && string(args[0]) == "--metadata") { // first argument
Bookatzff71cad2018-09-20 17:17:49 -0700225 // Request is to dump statsd stats.
226 bool verbose = false;
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800227 if (lastArg >= 0 && string(args[lastArg]) == "-v") {
Bookatzff71cad2018-09-20 17:17:49 -0700228 verbose = true;
229 lastArg--;
230 }
231 dumpStatsdStats(fd, verbose, asProto);
232 } else {
233 // Request is to dump statsd report data.
234 if (asProto) {
235 dumpIncidentSection(fd);
236 } else {
237 dprintf(fd, "Non-proto format of stats data dump not available; see proto version.\n");
238 }
Tej Singh41b3f9a2018-04-03 17:06:35 -0700239 }
Yao Chen884c8c12018-01-26 10:36:25 -0800240
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700241 return NO_ERROR;
242}
243
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700244/**
Tej Singh41b3f9a2018-04-03 17:06:35 -0700245 * Write debugging data about statsd in text or proto format.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700246 */
Bookatzff71cad2018-09-20 17:17:49 -0700247void StatsService::dumpStatsdStats(int out, bool verbose, bool proto) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700248 if (proto) {
249 vector<uint8_t> data;
250 StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
251 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700252 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700253 }
254 } else {
255 StatsdStats::getInstance().dumpStats(out);
256 mProcessor->dumpStates(out, verbose);
257 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700258}
259
260/**
Bookatzff71cad2018-09-20 17:17:49 -0700261 * Write stats report data in StatsDataDumpProto incident section format.
262 */
263void StatsService::dumpIncidentSection(int out) {
264 ProtoOutputStream proto;
265 for (const ConfigKey& configKey : mConfigManager->GetAllConfigKeys()) {
266 uint64_t reportsListToken =
267 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS_LIST);
268 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
269 true /* includeCurrentBucket */, false /* erase_data */,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000270 ADB_DUMP,
271 FAST,
272 &proto);
Bookatzff71cad2018-09-20 17:17:49 -0700273 proto.end(reportsListToken);
274 proto.flush(out);
Bookatzc71d9012018-12-19 12:28:38 -0800275 proto.clear();
Bookatzff71cad2018-09-20 17:17:49 -0700276 }
277}
278
279/**
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700280 * Implementation of the adb shell cmd stats command.
281 */
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800282status_t StatsService::handleShellCommand(int in, int out, int err, const char** argv,
283 uint32_t argc) {
284 uid_t uid = AIBinder_getCallingUid();
Stanislav Zholnind7674c22020-02-17 17:48:12 +0000285 if (uid != AID_ROOT && uid != AID_SHELL) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600286 return PERMISSION_DENIED;
287 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700288
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800289 Vector<String8> utf8Args;
290 utf8Args.setCapacity(argc);
291 for (uint32_t i = 0; i < argc; i++) {
292 utf8Args.push(String8(argv[i]));
293 }
294
295 if (argc >= 1) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700296 // adb shell cmd stats config ...
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800297 if (!utf8Args[0].compare(String8("config"))) {
298 return cmd_config(in, out, err, utf8Args);
David Chen0656b7a2017-09-13 15:53:39 -0700299 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700300
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800301 if (!utf8Args[0].compare(String8("print-uid-map"))) {
302 return cmd_print_uid_map(out, utf8Args);
David Chende701692017-10-05 13:16:02 -0700303 }
Yao Chen729093d2017-10-16 10:33:26 -0700304
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800305 if (!utf8Args[0].compare(String8("dump-report"))) {
306 return cmd_dump_report(out, utf8Args);
Yao Chen729093d2017-10-16 10:33:26 -0700307 }
David Chen1481fe12017-10-16 13:16:34 -0700308
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800309 if (!utf8Args[0].compare(String8("pull-source")) && argc > 1) {
310 return cmd_print_pulled_metrics(out, utf8Args);
David Chen1481fe12017-10-16 13:16:34 -0700311 }
David Chenadaf8b32017-11-03 15:42:08 -0700312
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800313 if (!utf8Args[0].compare(String8("send-broadcast"))) {
314 return cmd_trigger_broadcast(out, utf8Args);
David Chen1d7b0cd2017-11-15 14:20:04 -0800315 }
316
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800317 if (!utf8Args[0].compare(String8("print-stats"))) {
318 return cmd_print_stats(out, utf8Args);
David Chenadaf8b32017-11-03 15:42:08 -0700319 }
yro87d983c2017-11-14 21:31:43 -0800320
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800321 if (!utf8Args[0].compare(String8("meminfo"))) {
Yao Chen8d9989b2017-11-18 18:54:50 -0800322 return cmd_dump_memory_info(out);
323 }
yro947fbce2017-11-15 22:50:23 -0800324
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800325 if (!utf8Args[0].compare(String8("write-to-disk"))) {
yro947fbce2017-11-15 22:50:23 -0800326 return cmd_write_data_to_disk(out);
327 }
Bookatzb223c4e2018-02-01 15:35:04 -0800328
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800329 if (!utf8Args[0].compare(String8("log-app-breadcrumb"))) {
330 return cmd_log_app_breadcrumb(out, utf8Args);
Bookatzb223c4e2018-02-01 15:35:04 -0800331 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800332
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800333 if (!utf8Args[0].compare(String8("log-binary-push"))) {
334 return cmd_log_binary_push(out, utf8Args);
Tej Singh53f9dee2019-04-30 17:45:54 -0700335 }
336
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800337 if (!utf8Args[0].compare(String8("clear-puller-cache"))) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800338 return cmd_clear_puller_cache(out);
339 }
Yao Chen876889c2018-05-02 11:16:16 -0700340
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800341 if (!utf8Args[0].compare(String8("print-logs"))) {
342 return cmd_print_logs(out, utf8Args);
Yao Chen876889c2018-05-02 11:16:16 -0700343 }
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800344 if (!utf8Args[0].compare(String8("send-active-configs"))) {
345 return cmd_trigger_active_config_broadcast(out, utf8Args);
Tej Singh6ede28b2019-01-29 17:06:54 -0800346 }
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800347 if (!utf8Args[0].compare(String8("data-subscribe"))) {
Tej Singhc9250ce2019-09-20 19:28:53 -0700348 {
349 std::lock_guard<std::mutex> lock(mShellSubscriberMutex);
350 if (mShellSubscriber == nullptr) {
351 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
352 }
Yao Chena80e5c02018-09-04 13:55:29 -0700353 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800354 int timeoutSec = -1;
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800355 if (argc >= 2) {
356 timeoutSec = atoi(utf8Args[1].c_str());
Yao Chen35cb8d62019-01-03 16:49:14 -0800357 }
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800358 mShellSubscriber->startNewSubscription(in, out, timeoutSec);
Yao Chena80e5c02018-09-04 13:55:29 -0700359 return NO_ERROR;
360 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700361 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700362
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700363 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700364 return NO_ERROR;
365}
366
Yao Chena80e5c02018-09-04 13:55:29 -0700367void StatsService::print_cmd_help(int out) {
368 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700369 "usage: adb shell cmd stats print-stats-log [tag_required] "
370 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700371 dprintf(out, "\n");
372 dprintf(out, "\n");
373 dprintf(out, "usage: adb shell cmd stats meminfo\n");
374 dprintf(out, "\n");
375 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
376 dprintf(out, " # adb shell stop\n");
377 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
378 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
379 dprintf(out, " # adb shell start\n");
380 dprintf(out, "\n");
381 dprintf(out, "\n");
382 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
383 dprintf(out, "\n");
384 dprintf(out, " Prints the UID, app name, version mapping.\n");
385 dprintf(out, " PKG Optional package name to print the uids of the package\n");
386 dprintf(out, "\n");
387 dprintf(out, "\n");
388 dprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
389 dprintf(out, "\n");
390 dprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
391 dprintf(out, "\n");
392 dprintf(out, "\n");
393 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
394 dprintf(out, "\n");
395 dprintf(out, " Flushes all data on memory to disk.\n");
396 dprintf(out, "\n");
397 dprintf(out, "\n");
398 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
399 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
400 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
401 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
402 dprintf(out, " uid is used.\n");
403 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
404 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
405 dprintf(out, "\n");
406 dprintf(out, "\n");
Tej Singh53f9dee2019-04-30 17:45:54 -0700407 dprintf(out,
408 "usage: adb shell cmd stats log-binary-push NAME VERSION STAGING ROLLBACK_ENABLED "
409 "LOW_LATENCY STATE EXPERIMENT_IDS\n");
410 dprintf(out, " Log a binary push state changed event.\n");
411 dprintf(out, " NAME The train name.\n");
412 dprintf(out, " VERSION The train version code.\n");
413 dprintf(out, " STAGING If this train requires a restart.\n");
414 dprintf(out, " ROLLBACK_ENABLED If rollback should be enabled for this install.\n");
415 dprintf(out, " LOW_LATENCY If the train requires low latency monitoring.\n");
416 dprintf(out, " STATE The status of the train push.\n");
417 dprintf(out, " Integer value of the enum in atoms.proto.\n");
418 dprintf(out, " EXPERIMENT_IDS Comma separated list of experiment ids.\n");
419 dprintf(out, " Leave blank for none.\n");
420 dprintf(out, "\n");
421 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700422 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
423 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
424 dprintf(out, "\n");
425 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
426 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
427 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
428 dprintf(out, "\n");
429 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
430 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
431 dprintf(out, " uid is used.\n");
432 dprintf(out, " NAME The per-uid name to use\n");
433 dprintf(out, "\n");
434 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
435 dprintf(out, "\n be removed from memory and disk!\n");
436 dprintf(out, "\n");
437 dprintf(out,
Bookatz3e906582018-12-10 17:26:58 -0800438 "usage: adb shell cmd stats dump-report [UID] NAME [--keep_data] "
439 "[--include_current_bucket] [--proto]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700440 dprintf(out, " Dump all metric data for a configuration.\n");
441 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
442 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
443 dprintf(out, " calling uid is used.\n");
444 dprintf(out, " NAME The name of the configuration\n");
Bookatz3e906582018-12-10 17:26:58 -0800445 dprintf(out, " --keep_data Do NOT erase the data upon dumping it.\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700446 dprintf(out, " --proto Print proto binary.\n");
447 dprintf(out, "\n");
448 dprintf(out, "\n");
449 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
450 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
451 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
452 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
453 dprintf(out, " calling uid is used.\n");
454 dprintf(out, " NAME The name of the configuration\n");
455 dprintf(out, "\n");
456 dprintf(out, "\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800457 dprintf(out,
458 "usage: adb shell cmd stats send-active-configs [--uid=UID] [--configs] "
459 "[NAME1] [NAME2] [NAME3..]\n");
460 dprintf(out, " Send a broadcast that informs the subscriber of the current active configs.\n");
461 dprintf(out, " --uid=UID The uid of the configurations. It is only possible to pass\n");
462 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
463 dprintf(out, " calling uid is used.\n");
464 dprintf(out, " --configs Send the list of configs in the name list instead of\n");
465 dprintf(out, " the currently active configs\n");
466 dprintf(out, " NAME LIST List of configuration names to be included in the broadcast.\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800467 dprintf(out, "\n");
468 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700469 dprintf(out, "usage: adb shell cmd stats print-stats\n");
470 dprintf(out, " Prints some basic stats.\n");
471 dprintf(out, " --proto Print proto binary instead of string format.\n");
472 dprintf(out, "\n");
473 dprintf(out, "\n");
474 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
475 dprintf(out, " Clear cached puller data.\n");
476 dprintf(out, "\n");
477 dprintf(out, "usage: adb shell cmd stats print-logs\n");
478 dprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700479}
480
Yao Chena80e5c02018-09-04 13:55:29 -0700481status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800482 string name;
483 bool good = false;
484 int uid;
485 const int argCount = args.size();
486 if (argCount == 2) {
487 // Automatically pick the UID
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800488 uid = AIBinder_getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800489 name.assign(args[1].c_str(), args[1].size());
490 good = true;
491 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800492 good = getUidFromArgs(args, 1, uid);
493 if (!good) {
494 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
495 "other UIDs on eng or userdebug builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800496 }
Bookatzd2386572018-12-14 15:53:14 -0800497 name.assign(args[2].c_str(), args[2].size());
David Chen1d7b0cd2017-11-15 14:20:04 -0800498 }
499 if (!good) {
500 print_cmd_help(out);
501 return UNKNOWN_ERROR;
502 }
David Chend37bc232018-04-12 18:05:11 -0700503 ConfigKey key(uid, StrToInt64(name));
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800504 shared_ptr<IPendingIntentRef> receiver = mConfigManager->GetConfigReceiver(key);
Jeffrey Huangad213742019-12-16 13:50:06 -0800505 if (receiver == nullptr) {
506 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str());
507 return UNKNOWN_ERROR;
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800508 } else if (receiver->sendDataBroadcast(mProcessor->getLastReportTimeNs(key)).isOk()) {
yro74fed972017-11-27 14:42:42 -0800509 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
510 args[2].c_str());
Jeffrey Huangad213742019-12-16 13:50:06 -0800511 } else {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800512 VLOG("StatsService::trigger broadcast failed to %s, %s", args[1].c_str(), args[2].c_str());
Jeffrey Huangad213742019-12-16 13:50:06 -0800513 return UNKNOWN_ERROR;
yro4d889e62017-11-17 15:44:48 -0800514 }
David Chenadaf8b32017-11-03 15:42:08 -0700515 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700516}
517
Tej Singh6ede28b2019-01-29 17:06:54 -0800518status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
519 const int argCount = args.size();
520 int uid;
521 vector<int64_t> configIds;
522 if (argCount == 1) {
523 // Automatically pick the uid and send a broadcast that has no active configs.
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800524 uid = AIBinder_getCallingUid();
Tej Singh6ede28b2019-01-29 17:06:54 -0800525 mProcessor->GetActiveConfigs(uid, configIds);
526 } else {
527 int curArg = 1;
528 if(args[curArg].find("--uid=") == 0) {
529 string uidArgStr(args[curArg].c_str());
530 string uidStr = uidArgStr.substr(6);
531 if (!getUidFromString(uidStr.c_str(), uid)) {
532 dprintf(out, "Invalid UID. Note that the config can only be set for "
533 "other UIDs on eng or userdebug builds.\n");
534 return UNKNOWN_ERROR;
535 }
536 curArg++;
537 } else {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800538 uid = AIBinder_getCallingUid();
Tej Singh6ede28b2019-01-29 17:06:54 -0800539 }
540 if (curArg == argCount || args[curArg] != "--configs") {
541 VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
542 mProcessor->GetActiveConfigs(uid, configIds);
543 } else {
544 // Flag specified, use the given list of configs.
545 curArg++;
546 for (int i = curArg; i < argCount; i++) {
547 char* endp;
548 int64_t configID = strtoll(args[i].c_str(), &endp, 10);
549 if (endp == args[i].c_str() || *endp != '\0') {
550 dprintf(out, "Error parsing config ID.\n");
551 return UNKNOWN_ERROR;
552 }
553 VLOG("Adding config id %ld", static_cast<long>(configID));
554 configIds.push_back(configID);
555 }
556 }
557 }
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800558 shared_ptr<IPendingIntentRef> receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
Jeffrey Huang47537a12020-01-06 15:35:34 -0800559 if (receiver == nullptr) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800560 VLOG("Could not find receiver for uid %d", uid);
Jeffrey Huang47537a12020-01-06 15:35:34 -0800561 return UNKNOWN_ERROR;
562 } else if (receiver->sendActiveConfigsChangedBroadcast(configIds).isOk()) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800563 VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
Jeffrey Huang47537a12020-01-06 15:35:34 -0800564 } else {
565 VLOG("StatsService::trigger active configs changed broadcast failed for uid %d", uid);
566 return UNKNOWN_ERROR;
Tej Singh6ede28b2019-01-29 17:06:54 -0800567 }
568 return NO_ERROR;
569}
570
Yao Chena80e5c02018-09-04 13:55:29 -0700571status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700572 const int argCount = args.size();
573 if (argCount >= 2) {
574 if (args[1] == "update" || args[1] == "remove") {
575 bool good = false;
576 int uid = -1;
577 string name;
578
579 if (argCount == 3) {
580 // Automatically pick the UID
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800581 uid = AIBinder_getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700582 name.assign(args[2].c_str(), args[2].size());
583 good = true;
584 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800585 good = getUidFromArgs(args, 2, uid);
586 if (!good) {
587 dprintf(err, "Invalid UID. Note that the config can only be set for "
588 "other UIDs on eng or userdebug builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700589 }
Bookatzd2386572018-12-14 15:53:14 -0800590 name.assign(args[3].c_str(), args[3].size());
yroe5f82922018-01-22 18:37:27 -0800591 } else if (argCount == 2 && args[1] == "remove") {
592 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700593 }
594
595 if (!good) {
596 // If arg parsing failed, print the help text and return an error.
597 print_cmd_help(out);
598 return UNKNOWN_ERROR;
599 }
600
601 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800602 char* endp;
603 int64_t configID = strtoll(name.c_str(), &endp, 10);
604 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700605 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800606 return UNKNOWN_ERROR;
607 }
608
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700609 // Read stream into buffer.
610 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700611 if (!android::base::ReadFdToString(in, &buffer)) {
612 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700613 return UNKNOWN_ERROR;
614 }
615
616 // Parse buffer.
617 StatsdConfig config;
618 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700619 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700620 return UNKNOWN_ERROR;
621 }
622
623 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800624 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700625 } else {
yro74fed972017-11-27 14:42:42 -0800626 if (argCount == 2) {
627 cmd_remove_all_configs(out);
628 } else {
629 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800630 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800631 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700632 }
633
634 return NO_ERROR;
635 }
David Chen0656b7a2017-09-13 15:53:39 -0700636 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700637 print_cmd_help(out);
638 return UNKNOWN_ERROR;
639}
640
Bookatzff71cad2018-09-20 17:17:49 -0700641status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700642 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800643 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700644 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800645 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700646 bool includeCurrentBucket = false;
Bookatz3e906582018-12-10 17:26:58 -0800647 bool eraseData = true;
Yao Chen729093d2017-10-16 10:33:26 -0700648 int uid;
649 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800650 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
651 proto = true;
652 argCount -= 1;
653 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700654 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
655 includeCurrentBucket = true;
656 argCount -= 1;
657 }
Bookatz3e906582018-12-10 17:26:58 -0800658 if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
659 eraseData = false;
660 argCount -= 1;
661 }
Yao Chen729093d2017-10-16 10:33:26 -0700662 if (argCount == 2) {
663 // Automatically pick the UID
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800664 uid = AIBinder_getCallingUid();
Yao Chen5154a372017-10-30 22:57:06 -0700665 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700666 good = true;
667 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800668 good = getUidFromArgs(args, 1, uid);
669 if (!good) {
670 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
671 "other UIDs on eng or userdebug builds.\n");
Yao Chen729093d2017-10-16 10:33:26 -0700672 }
Bookatzd2386572018-12-14 15:53:14 -0800673 name.assign(args[2].c_str(), args[2].size());
Yao Chen729093d2017-10-16 10:33:26 -0700674 }
675 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800676 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800677 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000678 includeCurrentBucket, eraseData, ADB_DUMP,
679 NO_TIME_CONSTRAINTS,
680 &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800681 if (proto) {
682 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700683 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800684 }
685 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700686 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800687 }
Yao Chen729093d2017-10-16 10:33:26 -0700688 return android::OK;
689 } else {
690 // If arg parsing failed, print the help text and return an error.
691 print_cmd_help(out);
692 return UNKNOWN_ERROR;
693 }
694 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700695 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700696 return UNKNOWN_ERROR;
697 }
698}
699
Yao Chena80e5c02018-09-04 13:55:29 -0700700status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700701 int argCount = args.size();
702 bool proto = false;
703 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
704 proto = true;
705 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800706 }
Yao Chenb3561512017-11-21 18:07:17 -0800707 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700708 if (proto) {
709 vector<uint8_t> data;
710 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
711 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700712 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700713 }
714
715 } else {
716 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
717 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700718 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700719 mProcessor->GetMetricsSize(key));
720 }
721 statsdStats.dumpStats(out);
722 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800723 return NO_ERROR;
724}
725
Yao Chena80e5c02018-09-04 13:55:29 -0700726status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800727 if (args.size() > 1) {
728 string pkg;
729 pkg.assign(args[1].c_str(), args[1].size());
730 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700731 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800732 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700733 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800734 }
Yao Chena80e5c02018-09-04 13:55:29 -0700735 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800736 } else {
737 mUidMap->printUidMap(out);
738 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700739 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700740}
741
Yao Chena80e5c02018-09-04 13:55:29 -0700742status_t StatsService::cmd_write_data_to_disk(int out) {
743 dprintf(out, "Writing data to disk\n");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000744 mProcessor->WriteDataToDisk(ADB_DUMP, NO_TIME_CONSTRAINTS);
yro947fbce2017-11-15 22:50:23 -0800745 return NO_ERROR;
746}
747
Yao Chena80e5c02018-09-04 13:55:29 -0700748status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800749 bool good = false;
750 int32_t uid;
751 int32_t label;
752 int32_t state;
753 const int argCount = args.size();
754 if (argCount == 3) {
755 // Automatically pick the UID
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800756 uid = AIBinder_getCallingUid();
Bookatzb223c4e2018-02-01 15:35:04 -0800757 label = atoi(args[1].c_str());
758 state = atoi(args[2].c_str());
759 good = true;
760 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800761 good = getUidFromArgs(args, 1, uid);
762 if (!good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700763 dprintf(out,
Bookatzd2386572018-12-14 15:53:14 -0800764 "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
765 "done for other UIDs on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800766 }
Bookatzd2386572018-12-14 15:53:14 -0800767 label = atoi(args[2].c_str());
768 state = atoi(args[3].c_str());
Bookatzb223c4e2018-02-01 15:35:04 -0800769 }
770 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700771 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
Jeffrey Huang74fc4352020-03-06 15:18:33 -0800772 android::os::statsd::util::stats_write(
773 android::os::statsd::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800774 } else {
775 print_cmd_help(out);
776 return UNKNOWN_ERROR;
777 }
778 return NO_ERROR;
779}
780
Tej Singh53f9dee2019-04-30 17:45:54 -0700781status_t StatsService::cmd_log_binary_push(int out, const Vector<String8>& args) {
782 // Security checks are done in the sendBinaryPushStateChanged atom.
783 const int argCount = args.size();
784 if (argCount != 7 && argCount != 8) {
785 dprintf(out, "Incorrect number of argument supplied\n");
786 return UNKNOWN_ERROR;
787 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800788 string trainName = string(args[1].c_str());
Tej Singh53f9dee2019-04-30 17:45:54 -0700789 int64_t trainVersion = strtoll(args[2].c_str(), nullptr, 10);
Tej Singh53f9dee2019-04-30 17:45:54 -0700790 int32_t state = atoi(args[6].c_str());
791 vector<int64_t> experimentIds;
792 if (argCount == 8) {
793 vector<string> experimentIdsString = android::base::Split(string(args[7].c_str()), ",");
794 for (string experimentIdString : experimentIdsString) {
795 int64_t experimentId = strtoll(experimentIdString.c_str(), nullptr, 10);
796 experimentIds.push_back(experimentId);
797 }
798 }
799 dprintf(out, "Logging BinaryPushStateChanged\n");
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800800 vector<uint8_t> experimentIdBytes;
801 writeExperimentIdsToProto(experimentIds, &experimentIdBytes);
802 LogEvent event(trainName, trainVersion, args[3], args[4], args[5], state, experimentIdBytes, 0);
803 mProcessor->OnLogEvent(&event);
Tej Singh53f9dee2019-04-30 17:45:54 -0700804 return NO_ERROR;
805}
806
Yao Chena80e5c02018-09-04 13:55:29 -0700807status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700808 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700809 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800810 if (mPullerManager->Pull(s, &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700811 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700812 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700813 }
Yao Chena80e5c02018-09-04 13:55:29 -0700814 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700815 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700816 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700817 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700818}
819
Yao Chena80e5c02018-09-04 13:55:29 -0700820status_t StatsService::cmd_remove_all_configs(int out) {
821 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800822 VLOG("StatsService::cmd_remove_all_configs was called");
823 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800824 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800825 return NO_ERROR;
826}
827
Yao Chena80e5c02018-09-04 13:55:29 -0700828status_t StatsService::cmd_dump_memory_info(int out) {
829 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800830 return NO_ERROR;
831}
832
Yao Chena80e5c02018-09-04 13:55:29 -0700833status_t StatsService::cmd_clear_puller_cache(int out) {
Yangster-mac932ecec2018-02-01 10:23:52 -0800834 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800835 AIBinder_getCallingPid(), AIBinder_getCallingUid());
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -0800836 if (checkPermission(kPermissionDump)) {
Chenjie Yue2219202018-06-08 10:07:51 -0700837 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700838 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800839 return NO_ERROR;
840 } else {
841 return PERMISSION_DENIED;
842 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800843}
844
Yao Chena80e5c02018-09-04 13:55:29 -0700845status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800846 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", AIBinder_getCallingPid(),
847 AIBinder_getCallingUid());
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -0800848 if (checkPermission(kPermissionDump)) {
Yao Chen876889c2018-05-02 11:16:16 -0700849 bool enabled = true;
850 if (args.size() >= 2) {
851 enabled = atoi(args[1].c_str()) != 0;
852 }
853 mProcessor->setPrintLogs(enabled);
854 return NO_ERROR;
855 } else {
856 return PERMISSION_DENIED;
857 }
858}
859
Bookatzd2386572018-12-14 15:53:14 -0800860bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800861 return getUidFromString(args[uidArgIndex].c_str(), uid);
862}
863
864bool StatsService::getUidFromString(const char* s, int32_t& uid) {
Bookatzd2386572018-12-14 15:53:14 -0800865 if (*s == '\0') {
866 return false;
867 }
868 char* endc = NULL;
869 int64_t longUid = strtol(s, &endc, 0);
870 if (*endc != '\0') {
871 return false;
872 }
873 int32_t goodUid = static_cast<int32_t>(longUid);
874 if (longUid < 0 || static_cast<uint64_t>(longUid) != static_cast<uid_t>(goodUid)) {
875 return false; // It was not of uid_t type.
876 }
877 uid = goodUid;
878
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800879 int32_t callingUid = AIBinder_getCallingUid();
Bookatzd2386572018-12-14 15:53:14 -0800880 return mEngBuild // UserDebug/EngBuild are allowed to impersonate uids.
881 || (callingUid == goodUid) // Anyone can 'impersonate' themselves.
882 || (callingUid == AID_ROOT && goodUid == AID_SHELL); // ROOT can impersonate SHELL.
883}
884
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800885Status StatsService::informAllUidData(const ScopedFileDescriptor& fd) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600886 ENFORCE_UID(AID_SYSTEM);
Max Dashouk11e0d402019-05-16 16:58:07 -0700887 // Read stream into buffer.
888 string buffer;
889 if (!android::base::ReadFdToString(fd.get(), &buffer)) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800890 return exception(EX_ILLEGAL_ARGUMENT, "Failed to read all data from the pipe.");
Max Dashouk11e0d402019-05-16 16:58:07 -0700891 }
Jeff Sharkey6b649252018-04-16 09:50:22 -0600892
Max Dashouk11e0d402019-05-16 16:58:07 -0700893 // Parse buffer.
894 UidData uidData;
895 if (!uidData.ParseFromString(buffer)) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800896 return exception(EX_ILLEGAL_ARGUMENT, "Error parsing proto stream for UidData.");
Max Dashouk11e0d402019-05-16 16:58:07 -0700897 }
David Chende701692017-10-05 13:16:02 -0700898
Max Dashouk11e0d402019-05-16 16:58:07 -0700899 vector<String16> versionStrings;
900 vector<String16> installers;
901 vector<String16> packageNames;
902 vector<int32_t> uids;
903 vector<int64_t> versions;
904
905 const auto numEntries = uidData.app_info_size();
906 versionStrings.reserve(numEntries);
907 installers.reserve(numEntries);
908 packageNames.reserve(numEntries);
909 uids.reserve(numEntries);
910 versions.reserve(numEntries);
911
912 for (const auto& appInfo: uidData.app_info()) {
913 packageNames.emplace_back(String16(appInfo.package_name().c_str()));
914 uids.push_back(appInfo.uid());
915 versions.push_back(appInfo.version());
916 versionStrings.emplace_back(String16(appInfo.version_string().c_str()));
917 installers.emplace_back(String16(appInfo.installer().c_str()));
918 }
919
920 mUidMap->updateMap(getElapsedRealtimeNs(),
921 uids,
922 versions,
923 versionStrings,
924 packageNames,
925 installers);
926
927 VLOG("StatsService::informAllUidData UidData proto parsed successfully.");
David Chende701692017-10-05 13:16:02 -0700928 return Status::ok();
929}
930
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800931Status StatsService::informOnePackage(const string& app, int32_t uid, int64_t version,
932 const string& versionString, const string& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600933 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700934
Jeff Sharkey6b649252018-04-16 09:50:22 -0600935 VLOG("StatsService::informOnePackage was called");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800936 String16 utf16App = String16(app.c_str());
937 String16 utf16VersionString = String16(versionString.c_str());
938 String16 utf16Installer = String16(installer.c_str());
939
940 mUidMap->updateApp(getElapsedRealtimeNs(), utf16App, uid, version, utf16VersionString,
941 utf16Installer);
David Chende701692017-10-05 13:16:02 -0700942 return Status::ok();
943}
944
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800945Status StatsService::informOnePackageRemoved(const string& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600946 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700947
Jeff Sharkey6b649252018-04-16 09:50:22 -0600948 VLOG("StatsService::informOnePackageRemoved was called");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800949 String16 utf16App = String16(app.c_str());
950 mUidMap->removeApp(getElapsedRealtimeNs(), utf16App, uid);
yro01924022018-02-20 18:20:49 -0800951 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -0700952 return Status::ok();
953}
954
Yao Chenef99c4f2017-09-22 16:26:54 -0700955Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600956 ENFORCE_UID(AID_SYSTEM);
957
yro74fed972017-11-27 14:42:42 -0800958 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700959 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800960 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
961 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
962 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -0800963 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -0800964 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -0800965 } else {
966 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
967 }
Bookatz1b0b1142017-09-08 11:58:42 -0700968 return Status::ok();
969}
970
Yangster-mac932ecec2018-02-01 10:23:52 -0800971Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600972 ENFORCE_UID(AID_SYSTEM);
973
Yangster-mac932ecec2018-02-01 10:23:52 -0800974 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700975 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800976 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
977 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
978 if (alarmSet.size() > 0) {
979 VLOG("Found periodic alarm fired.");
980 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
981 } else {
982 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
983 }
984 return Status::ok();
985}
986
Yao Chenef99c4f2017-09-22 16:26:54 -0700987Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600988 ENFORCE_UID(AID_SYSTEM);
989
yro74fed972017-11-27 14:42:42 -0800990 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700991 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -0800992 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700993 return Status::ok();
994}
995
Yao Chenef99c4f2017-09-22 16:26:54 -0700996Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600997 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700998
999 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -08001000 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -07001001 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001002 return Status::ok();
1003}
1004
Yangster-mac892f3d32018-05-02 14:16:48 -07001005Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001006 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -07001007 VLOG("StatsService::informDeviceShutdown");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001008 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001009 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
Jeffrey Huangb8f54032020-03-23 13:42:42 -07001010 mProcessor->SaveMetadataToDisk(getWallClockNs(), getElapsedRealtimeNs());
yro947fbce2017-11-15 22:50:23 -08001011 return Status::ok();
1012}
1013
Yao Chenef99c4f2017-09-22 16:26:54 -07001014void StatsService::sayHiToStatsCompanion() {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001015 shared_ptr<IStatsCompanionService> statsCompanion = getStatsCompanionService();
Bookatzb487b552017-09-18 11:26:01 -07001016 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -08001017 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -07001018 statsCompanion->statsdReady();
1019 } else {
yro74fed972017-11-27 14:42:42 -08001020 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -07001021 }
1022}
1023
Yao Chenef99c4f2017-09-22 16:26:54 -07001024Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001025 ENFORCE_UID(AID_SYSTEM);
1026
yro74fed972017-11-27 14:42:42 -08001027 VLOG("StatsService::statsCompanionReady was called");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001028 shared_ptr<IStatsCompanionService> statsCompanion = getStatsCompanionService();
Bookatzb487b552017-09-18 11:26:01 -07001029 if (statsCompanion == nullptr) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001030 return exception(EX_NULL_POINTER,
1031 "StatsCompanion unavailable despite it contacting statsd.");
Bookatzb487b552017-09-18 11:26:01 -07001032 }
yro74fed972017-11-27 14:42:42 -08001033 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001034 AIBinder_linkToDeath(statsCompanion->asBinder().get(),
1035 mStatsCompanionServiceDeathRecipient.get(), this);
Chenjie Yue2219202018-06-08 10:07:51 -07001036 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -08001037 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
1038 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -07001039 return Status::ok();
1040}
1041
Joe Onorato9fc9edf2017-10-15 20:08:52 -07001042void StatsService::Startup() {
1043 mConfigManager->Startup();
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001044 mProcessor->LoadActiveConfigsFromDisk();
Bookatz906a35c2017-09-20 15:26:44 -07001045}
1046
Yangster-mac97e7d202018-10-09 11:05:39 -07001047void StatsService::Terminate() {
1048 ALOGI("StatsService::Terminating");
1049 if (mProcessor != nullptr) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001050 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001051 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
Jeffrey Huangb8f54032020-03-23 13:42:42 -07001052 mProcessor->SaveMetadataToDisk(getWallClockNs(), getElapsedRealtimeNs());
Yangster-mac97e7d202018-10-09 11:05:39 -07001053 }
1054}
1055
Yao Chen0f861862019-03-27 11:51:15 -07001056// Test only interface!!!
Yao Chen3ff3a492018-08-06 16:17:37 -07001057void StatsService::OnLogEvent(LogEvent* event) {
1058 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -07001059 if (mShellSubscriber != nullptr) {
1060 mShellSubscriber->onLogEvent(*event);
1061 }
Bookatz906a35c2017-09-20 15:26:44 -07001062}
1063
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001064Status StatsService::getData(int64_t key, const int32_t callingUid, vector<int8_t>* output) {
Jeffrey Huang04f948b2020-01-07 10:05:25 -08001065 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001066
Jeffrey Huang04f948b2020-01-07 10:05:25 -08001067 VLOG("StatsService::getData with Uid %i", callingUid);
1068 ConfigKey configKey(callingUid, key);
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001069 // TODO(b/149254662): Since libbinder_ndk uses int8_t instead of uint8_t,
1070 // there are inconsistencies with internal statsd logic. Instead of
1071 // modifying lots of files, we create a temporary output array of int8_t and
1072 // copy its data into output. This is a bad hack, but hopefully
1073 // libbinder_ndk will transition to using uint8_t soon: progress is tracked
1074 // in b/144957764. Same applies to StatsService::getMetadata.
1075 vector<uint8_t> unsignedOutput;
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001076 // The dump latency does not matter here since we do not include the current bucket, we do not
1077 // need to pull any new data anyhow.
David Chen56ae0d92018-05-11 16:00:22 -07001078 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001079 true /* erase_data */, GET_DATA_CALLED, FAST, &unsignedOutput);
1080 *output = vector<int8_t>(unsignedOutput.begin(), unsignedOutput.end());
Bookatz4f716292018-04-10 17:15:12 -07001081 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001082}
1083
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001084Status StatsService::getMetadata(vector<int8_t>* output) {
Jeffrey Huang9613a972020-01-07 10:05:03 -08001085 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001086
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001087 vector<uint8_t> unsignedOutput;
1088 StatsdStats::getInstance().dumpStats(&unsignedOutput, false); // Don't reset the counters.
1089 *output = vector<int8_t>(unsignedOutput.begin(), unsignedOutput.end());
Bookatz4f716292018-04-10 17:15:12 -07001090 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -08001091}
1092
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001093Status StatsService::addConfiguration(int64_t key, const vector <int8_t>& config,
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001094 const int32_t callingUid) {
1095 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001096
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001097 if (addConfigurationChecked(callingUid, key, config)) {
David Chen661f7912018-01-22 17:46:24 -08001098 return Status::ok();
1099 } else {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001100 return exception(EX_ILLEGAL_ARGUMENT, "Could not parse malformatted StatsdConfig.");
David Chen661f7912018-01-22 17:46:24 -08001101 }
1102}
1103
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001104bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<int8_t>& config) {
David Chen9fdd4032018-03-20 14:38:56 -07001105 ConfigKey configKey(uid, key);
1106 StatsdConfig cfg;
1107 if (config.size() > 0) { // If the config is empty, skip parsing.
1108 if (!cfg.ParseFromArray(&config[0], config.size())) {
1109 return false;
1110 }
1111 }
1112 mConfigManager->UpdateConfig(configKey, cfg);
1113 return true;
1114}
1115
Jeffrey Huangad213742019-12-16 13:50:06 -08001116Status StatsService::removeDataFetchOperation(int64_t key,
1117 const int32_t callingUid) {
1118 ENFORCE_UID(AID_SYSTEM);
1119 ConfigKey configKey(callingUid, key);
Bookatz4f716292018-04-10 17:15:12 -07001120 mConfigManager->RemoveConfigReceiver(configKey);
1121 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -08001122}
1123
Jeff Sharkey6b649252018-04-16 09:50:22 -06001124Status StatsService::setDataFetchOperation(int64_t key,
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001125 const shared_ptr<IPendingIntentRef>& pir,
Jeffrey Huangad213742019-12-16 13:50:06 -08001126 const int32_t callingUid) {
1127 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001128
Jeffrey Huangad213742019-12-16 13:50:06 -08001129 ConfigKey configKey(callingUid, key);
1130 mConfigManager->SetConfigReceiver(configKey, pir);
David Chen48944902018-05-03 10:29:11 -07001131 if (StorageManager::hasConfigMetricsReport(configKey)) {
1132 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
1133 configKey.ToString().c_str());
1134 mProcessor->noteOnDiskData(configKey);
1135 }
Bookatz4f716292018-04-10 17:15:12 -07001136 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001137}
1138
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001139Status StatsService::setActiveConfigsChangedOperation(const shared_ptr<IPendingIntentRef>& pir,
Jeffrey Huang47537a12020-01-06 15:35:34 -08001140 const int32_t callingUid,
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001141 vector<int64_t>* output) {
Jeffrey Huang47537a12020-01-06 15:35:34 -08001142 ENFORCE_UID(AID_SYSTEM);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001143
Jeffrey Huang47537a12020-01-06 15:35:34 -08001144 mConfigManager->SetActiveConfigsChangedReceiver(callingUid, pir);
Tej Singh6ede28b2019-01-29 17:06:54 -08001145 if (output != nullptr) {
Jeffrey Huang47537a12020-01-06 15:35:34 -08001146 mProcessor->GetActiveConfigs(callingUid, *output);
Tej Singh6ede28b2019-01-29 17:06:54 -08001147 } else {
1148 ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
1149 }
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001150 return Status::ok();
1151}
1152
Jeffrey Huang47537a12020-01-06 15:35:34 -08001153Status StatsService::removeActiveConfigsChangedOperation(const int32_t callingUid) {
1154 ENFORCE_UID(AID_SYSTEM);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001155
Jeffrey Huang47537a12020-01-06 15:35:34 -08001156 mConfigManager->RemoveActiveConfigsChangedReceiver(callingUid);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001157 return Status::ok();
1158}
1159
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001160Status StatsService::removeConfiguration(int64_t key, const int32_t callingUid) {
1161 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001162
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001163 ConfigKey configKey(callingUid, key);
Bookatz4f716292018-04-10 17:15:12 -07001164 mConfigManager->RemoveConfig(configKey);
Bookatz4f716292018-04-10 17:15:12 -07001165 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001166}
1167
Bookatzc6977972018-01-16 16:55:05 -08001168Status StatsService::setBroadcastSubscriber(int64_t configId,
1169 int64_t subscriberId,
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001170 const shared_ptr<IPendingIntentRef>& pir,
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001171 const int32_t callingUid) {
1172 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001173
Bookatzc6977972018-01-16 16:55:05 -08001174 VLOG("StatsService::setBroadcastSubscriber called.");
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001175 ConfigKey configKey(callingUid, configId);
Bookatz4f716292018-04-10 17:15:12 -07001176 SubscriberReporter::getInstance()
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001177 .setBroadcastSubscriber(configKey, subscriberId, pir);
Bookatz4f716292018-04-10 17:15:12 -07001178 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001179}
1180
1181Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001182 int64_t subscriberId,
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001183 const int32_t callingUid) {
1184 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001185
Bookatzc6977972018-01-16 16:55:05 -08001186 VLOG("StatsService::unsetBroadcastSubscriber called.");
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001187 ConfigKey configKey(callingUid, configId);
Bookatz4f716292018-04-10 17:15:12 -07001188 SubscriberReporter::getInstance()
1189 .unsetBroadcastSubscriber(configKey, subscriberId);
1190 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001191}
1192
yrobe6d7f92018-05-04 13:02:53 -07001193Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
1194 // Permission check not necessary as it's meant for applications to write to
1195 // statsd.
Jeffrey Huang74fc4352020-03-06 15:18:33 -08001196 android::os::statsd::util::stats_write(android::os::statsd::util::APP_BREADCRUMB_REPORTED,
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001197 (int32_t) AIBinder_getCallingUid(), label,
yrobe6d7f92018-05-04 13:02:53 -07001198 state);
1199 return Status::ok();
1200}
1201
Tej Singh72a70a82020-02-26 23:46:29 -08001202Status StatsService::registerPullAtomCallback(int32_t uid, int32_t atomTag, int64_t coolDownMillis,
1203 int64_t timeoutMillis,
1204 const std::vector<int32_t>& additiveFields,
1205 const shared_ptr<IPullAtomCallback>& pullerCallback) {
Tej Singh6a5c9432019-10-11 11:07:06 -07001206 ENFORCE_UID(AID_SYSTEM);
Tej Singhb7802512019-12-04 17:57:04 -08001207 VLOG("StatsService::registerPullAtomCallback called.");
Tej Singh72a70a82020-02-26 23:46:29 -08001208 mPullerManager->RegisterPullAtomCallback(uid, atomTag, MillisToNano(coolDownMillis),
1209 MillisToNano(timeoutMillis), additiveFields,
Tej Singhb7802512019-12-04 17:57:04 -08001210 pullerCallback);
1211 return Status::ok();
1212}
1213
Tej Singh73597dc2020-03-13 18:42:40 -07001214Status StatsService::registerNativePullAtomCallback(
1215 int32_t atomTag, int64_t coolDownMillis, int64_t timeoutMillis,
1216 const std::vector<int32_t>& additiveFields,
1217 const shared_ptr<IPullAtomCallback>& pullerCallback) {
Tej Singh10458ec2020-03-17 11:04:02 -07001218 if (!checkPermission(kPermissionRegisterPullAtom)) {
1219 return exception(
1220 EX_SECURITY,
1221 StringPrintf("Uid %d does not have the %s permission when registering atom %d",
1222 AIBinder_getCallingUid(), kPermissionRegisterPullAtom, atomTag));
1223 }
Tej Singhb7802512019-12-04 17:57:04 -08001224 VLOG("StatsService::registerNativePullAtomCallback called.");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001225 int32_t uid = AIBinder_getCallingUid();
Tej Singh73597dc2020-03-13 18:42:40 -07001226 mPullerManager->RegisterPullAtomCallback(uid, atomTag, MillisToNano(coolDownMillis),
1227 MillisToNano(timeoutMillis), additiveFields,
Tej Singh6a5c9432019-10-11 11:07:06 -07001228 pullerCallback);
Tej Singh59184292019-10-11 11:07:06 -07001229 return Status::ok();
1230}
1231
Tej Singhfa1c1372019-12-05 20:36:54 -08001232Status StatsService::unregisterPullAtomCallback(int32_t uid, int32_t atomTag) {
1233 ENFORCE_UID(AID_SYSTEM);
1234 VLOG("StatsService::unregisterPullAtomCallback called.");
1235 mPullerManager->UnregisterPullAtomCallback(uid, atomTag);
1236 return Status::ok();
1237}
1238
Tej Singh8f358602020-01-15 16:05:39 -08001239Status StatsService::unregisterNativePullAtomCallback(int32_t atomTag) {
Tej Singh10458ec2020-03-17 11:04:02 -07001240 if (!checkPermission(kPermissionRegisterPullAtom)) {
1241 return exception(
1242 EX_SECURITY,
1243 StringPrintf("Uid %d does not have the %s permission when unregistering atom %d",
1244 AIBinder_getCallingUid(), kPermissionRegisterPullAtom, atomTag));
1245 }
Tej Singh8f358602020-01-15 16:05:39 -08001246 VLOG("StatsService::unregisterNativePullAtomCallback called.");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001247 int32_t uid = AIBinder_getCallingUid();
Tej Singh8f358602020-01-15 16:05:39 -08001248 mPullerManager->UnregisterPullAtomCallback(uid, atomTag);
1249 return Status::ok();
1250}
1251
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001252Status StatsService::getRegisteredExperimentIds(std::vector<int64_t>* experimentIdsOut) {
Jeffrey Huang80c9a972020-01-07 10:04:27 -08001253 ENFORCE_UID(AID_SYSTEM);
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001254 // TODO: add verifier permission
1255
Jonathan Nguyen703c42f2020-02-04 15:54:26 -08001256 experimentIdsOut->clear();
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001257 // Read the latest train info
Jonathan Nguyen703c42f2020-02-04 15:54:26 -08001258 vector<InstallTrainInfo> trainInfoList = StorageManager::readAllTrainInfo();
1259 if (trainInfoList.empty()) {
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001260 // No train info means no experiment IDs, return an empty list
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001261 return Status::ok();
1262 }
1263
1264 // Copy the experiment IDs to the out vector
Jonathan Nguyen703c42f2020-02-04 15:54:26 -08001265 for (InstallTrainInfo& trainInfo : trainInfoList) {
1266 experimentIdsOut->insert(experimentIdsOut->end(),
1267 trainInfo.experimentIds.begin(),
1268 trainInfo.experimentIds.end());
1269 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001270 return Status::ok();
1271}
1272
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001273
1274void StatsService::statsCompanionServiceDied(void* cookie) {
1275 auto thiz = static_cast<StatsService*>(cookie);
1276 thiz->statsCompanionServiceDiedImpl();
1277}
1278
1279void StatsService::statsCompanionServiceDiedImpl() {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001280 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001281 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1282 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001283 ALOGW("Reset statsd upon system server restarts.");
Tej Singhf53d4452019-05-09 18:17:59 -07001284 int64_t systemServerRestartNs = getElapsedRealtimeNs();
Jeffrey Huangb8f54032020-03-23 13:42:42 -07001285 ProtoOutputStream activeConfigsProto;
Tej Singhf53d4452019-05-09 18:17:59 -07001286 mProcessor->WriteActiveConfigsToProtoOutputStream(systemServerRestartNs,
Jeffrey Huangb8f54032020-03-23 13:42:42 -07001287 STATSCOMPANION_DIED, &activeConfigsProto);
1288 metadata::StatsMetadataList metadataList;
1289 mProcessor->WriteMetadataToProto(getWallClockNs(),
1290 systemServerRestartNs, &metadataList);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001291 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED, FAST);
Yangster-mac892f3d32018-05-02 14:16:48 -07001292 mProcessor->resetConfigs();
Tej Singhf53d4452019-05-09 18:17:59 -07001293
1294 std::string serializedActiveConfigs;
Jeffrey Huangb8f54032020-03-23 13:42:42 -07001295 if (activeConfigsProto.serializeToString(&serializedActiveConfigs)) {
Tej Singhf53d4452019-05-09 18:17:59 -07001296 ActiveConfigList activeConfigs;
1297 if (activeConfigs.ParseFromString(serializedActiveConfigs)) {
1298 mProcessor->SetConfigsActiveState(activeConfigs, systemServerRestartNs);
1299 }
1300 }
Yangster-mac892f3d32018-05-02 14:16:48 -07001301 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001302 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1303 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001304 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001305}
1306
Yao Chenef99c4f2017-09-22 16:26:54 -07001307} // namespace statsd
1308} // namespace os
1309} // namespace android