blob: f18aaa5a9ea0ce68cae1da1ba8484b8a346335d4 [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>
Bookatzb223c4e2018-02-01 15:35:04 -080035#include <statslog.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
yro03faf092017-12-12 00:17:50 -080056#define STATS_SERVICE_DIR "/data/misc/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070057
Bookatzff71cad2018-09-20 17:17:49 -070058// for StatsDataDumpProto
59const int FIELD_ID_REPORTS_LIST = 1;
60
Ruchir Rastogie449b0c2020-02-10 17:40:09 -080061static Status exception(int32_t code, const std::string& msg) {
Jeff Sharkey6b649252018-04-16 09:50:22 -060062 ALOGE("%s (%d)", msg.c_str(), code);
Ruchir Rastogie449b0c2020-02-10 17:40:09 -080063 return ::ndk::ScopedAStatus(AStatus_fromExceptionCodeWithMessage(code, msg.c_str()));
Jeff Sharkey6b649252018-04-16 09:50:22 -060064}
65
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -080066static bool checkPermission(const char* permission) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -080067 pid_t pid = AIBinder_getCallingPid();
68 uid_t uid = AIBinder_getCallingUid();
Jonathan Nguyena0e6de12020-01-28 18:33:55 -080069 return checkPermissionForIds(permission, pid, uid);
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -080070}
71
Ruchir Rastogie449b0c2020-02-10 17:40:09 -080072Status checkUid(uid_t expectedUid) {
73 uid_t uid = AIBinder_getCallingUid();
Jeff Sharkey6b649252018-04-16 09:50:22 -060074 if (uid == expectedUid || uid == AID_ROOT) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -080075 return Status::ok();
Jeff Sharkey6b649252018-04-16 09:50:22 -060076 } else {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -080077 return exception(EX_SECURITY,
78 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
Jeff Sharkey6b649252018-04-16 09:50:22 -060079 }
80}
81
82#define ENFORCE_UID(uid) { \
Ruchir Rastogie449b0c2020-02-10 17:40:09 -080083 Status status = checkUid((uid)); \
Jeff Sharkey6b649252018-04-16 09:50:22 -060084 if (!status.isOk()) { \
85 return status; \
86 } \
87}
88
Yao Chen0f861862019-03-27 11:51:15 -070089StatsService::StatsService(const sp<Looper>& handlerLooper, shared_ptr<LogEventQueue> queue)
90 : mAnomalyAlarmMonitor(new AlarmMonitor(
91 MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
Ruchir Rastogie449b0c2020-02-10 17:40:09 -080092 [](const shared_ptr<IStatsCompanionService>& sc, int64_t timeMillis) {
Yao Chen0f861862019-03-27 11:51:15 -070093 if (sc != nullptr) {
94 sc->setAnomalyAlarm(timeMillis);
95 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
96 }
97 },
Ruchir Rastogie449b0c2020-02-10 17:40:09 -080098 [](const shared_ptr<IStatsCompanionService>& sc) {
Yao Chen0f861862019-03-27 11:51:15 -070099 if (sc != nullptr) {
100 sc->cancelAnomalyAlarm();
101 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
102 }
103 })),
104 mPeriodicAlarmMonitor(new AlarmMonitor(
105 MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800106 [](const shared_ptr<IStatsCompanionService>& sc, int64_t timeMillis) {
Yao Chen0f861862019-03-27 11:51:15 -0700107 if (sc != nullptr) {
108 sc->setAlarmForSubscriberTriggering(timeMillis);
109 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
110 }
111 },
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800112 [](const shared_ptr<IStatsCompanionService>& sc) {
Yao Chen0f861862019-03-27 11:51:15 -0700113 if (sc != nullptr) {
114 sc->cancelAlarmForSubscriberTriggering();
115 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
116 }
117 })),
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800118 mEventQueue(queue),
119 mStatsCompanionServiceDeathRecipient(AIBinder_DeathRecipient_new(
120 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);
266 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
267 true /* includeCurrentBucket */, false /* erase_data */,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000268 ADB_DUMP,
269 FAST,
270 &proto);
Bookatzff71cad2018-09-20 17:17:49 -0700271 proto.end(reportsListToken);
272 proto.flush(out);
Bookatzc71d9012018-12-19 12:28:38 -0800273 proto.clear();
Bookatzff71cad2018-09-20 17:17:49 -0700274 }
275}
276
277/**
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700278 * Implementation of the adb shell cmd stats command.
279 */
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800280status_t StatsService::handleShellCommand(int in, int out, int err, const char** argv,
281 uint32_t argc) {
282 uid_t uid = AIBinder_getCallingUid();
Stanislav Zholnind7674c22020-02-17 17:48:12 +0000283 if (uid != AID_ROOT && uid != AID_SHELL) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600284 return PERMISSION_DENIED;
285 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700286
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800287 Vector<String8> utf8Args;
288 utf8Args.setCapacity(argc);
289 for (uint32_t i = 0; i < argc; i++) {
290 utf8Args.push(String8(argv[i]));
291 }
292
293 if (argc >= 1) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700294 // adb shell cmd stats config ...
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800295 if (!utf8Args[0].compare(String8("config"))) {
296 return cmd_config(in, out, err, utf8Args);
David Chen0656b7a2017-09-13 15:53:39 -0700297 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700298
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800299 if (!utf8Args[0].compare(String8("print-uid-map"))) {
300 return cmd_print_uid_map(out, utf8Args);
David Chende701692017-10-05 13:16:02 -0700301 }
Yao Chen729093d2017-10-16 10:33:26 -0700302
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800303 if (!utf8Args[0].compare(String8("dump-report"))) {
304 return cmd_dump_report(out, utf8Args);
Yao Chen729093d2017-10-16 10:33:26 -0700305 }
David Chen1481fe12017-10-16 13:16:34 -0700306
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800307 if (!utf8Args[0].compare(String8("pull-source")) && argc > 1) {
308 return cmd_print_pulled_metrics(out, utf8Args);
David Chen1481fe12017-10-16 13:16:34 -0700309 }
David Chenadaf8b32017-11-03 15:42:08 -0700310
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800311 if (!utf8Args[0].compare(String8("send-broadcast"))) {
312 return cmd_trigger_broadcast(out, utf8Args);
David Chen1d7b0cd2017-11-15 14:20:04 -0800313 }
314
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800315 if (!utf8Args[0].compare(String8("print-stats"))) {
316 return cmd_print_stats(out, utf8Args);
David Chenadaf8b32017-11-03 15:42:08 -0700317 }
yro87d983c2017-11-14 21:31:43 -0800318
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800319 if (!utf8Args[0].compare(String8("meminfo"))) {
Yao Chen8d9989b2017-11-18 18:54:50 -0800320 return cmd_dump_memory_info(out);
321 }
yro947fbce2017-11-15 22:50:23 -0800322
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800323 if (!utf8Args[0].compare(String8("write-to-disk"))) {
yro947fbce2017-11-15 22:50:23 -0800324 return cmd_write_data_to_disk(out);
325 }
Bookatzb223c4e2018-02-01 15:35:04 -0800326
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800327 if (!utf8Args[0].compare(String8("log-app-breadcrumb"))) {
328 return cmd_log_app_breadcrumb(out, utf8Args);
Bookatzb223c4e2018-02-01 15:35:04 -0800329 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800330
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800331 if (!utf8Args[0].compare(String8("log-binary-push"))) {
332 return cmd_log_binary_push(out, utf8Args);
Tej Singh53f9dee2019-04-30 17:45:54 -0700333 }
334
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800335 if (!utf8Args[0].compare(String8("clear-puller-cache"))) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800336 return cmd_clear_puller_cache(out);
337 }
Yao Chen876889c2018-05-02 11:16:16 -0700338
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800339 if (!utf8Args[0].compare(String8("print-logs"))) {
340 return cmd_print_logs(out, utf8Args);
Yao Chen876889c2018-05-02 11:16:16 -0700341 }
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800342 if (!utf8Args[0].compare(String8("send-active-configs"))) {
343 return cmd_trigger_active_config_broadcast(out, utf8Args);
Tej Singh6ede28b2019-01-29 17:06:54 -0800344 }
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800345 if (!utf8Args[0].compare(String8("data-subscribe"))) {
Tej Singhc9250ce2019-09-20 19:28:53 -0700346 {
347 std::lock_guard<std::mutex> lock(mShellSubscriberMutex);
348 if (mShellSubscriber == nullptr) {
349 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
350 }
Yao Chena80e5c02018-09-04 13:55:29 -0700351 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800352 int timeoutSec = -1;
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800353 if (argc >= 2) {
354 timeoutSec = atoi(utf8Args[1].c_str());
Yao Chen35cb8d62019-01-03 16:49:14 -0800355 }
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800356 mShellSubscriber->startNewSubscription(in, out, timeoutSec);
Yao Chena80e5c02018-09-04 13:55:29 -0700357 return NO_ERROR;
358 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700359 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700360
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700361 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700362 return NO_ERROR;
363}
364
Yao Chena80e5c02018-09-04 13:55:29 -0700365void StatsService::print_cmd_help(int out) {
366 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700367 "usage: adb shell cmd stats print-stats-log [tag_required] "
368 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700369 dprintf(out, "\n");
370 dprintf(out, "\n");
371 dprintf(out, "usage: adb shell cmd stats meminfo\n");
372 dprintf(out, "\n");
373 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
374 dprintf(out, " # adb shell stop\n");
375 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
376 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
377 dprintf(out, " # adb shell start\n");
378 dprintf(out, "\n");
379 dprintf(out, "\n");
380 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
381 dprintf(out, "\n");
382 dprintf(out, " Prints the UID, app name, version mapping.\n");
383 dprintf(out, " PKG Optional package name to print the uids of the package\n");
384 dprintf(out, "\n");
385 dprintf(out, "\n");
386 dprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
387 dprintf(out, "\n");
388 dprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
389 dprintf(out, "\n");
390 dprintf(out, "\n");
391 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
392 dprintf(out, "\n");
393 dprintf(out, " Flushes all data on memory to disk.\n");
394 dprintf(out, "\n");
395 dprintf(out, "\n");
396 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
397 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
398 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
399 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
400 dprintf(out, " uid is used.\n");
401 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
402 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
403 dprintf(out, "\n");
404 dprintf(out, "\n");
Tej Singh53f9dee2019-04-30 17:45:54 -0700405 dprintf(out,
406 "usage: adb shell cmd stats log-binary-push NAME VERSION STAGING ROLLBACK_ENABLED "
407 "LOW_LATENCY STATE EXPERIMENT_IDS\n");
408 dprintf(out, " Log a binary push state changed event.\n");
409 dprintf(out, " NAME The train name.\n");
410 dprintf(out, " VERSION The train version code.\n");
411 dprintf(out, " STAGING If this train requires a restart.\n");
412 dprintf(out, " ROLLBACK_ENABLED If rollback should be enabled for this install.\n");
413 dprintf(out, " LOW_LATENCY If the train requires low latency monitoring.\n");
414 dprintf(out, " STATE The status of the train push.\n");
415 dprintf(out, " Integer value of the enum in atoms.proto.\n");
416 dprintf(out, " EXPERIMENT_IDS Comma separated list of experiment ids.\n");
417 dprintf(out, " Leave blank for none.\n");
418 dprintf(out, "\n");
419 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700420 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
421 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
422 dprintf(out, "\n");
423 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
424 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
425 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
426 dprintf(out, "\n");
427 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
428 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
429 dprintf(out, " uid is used.\n");
430 dprintf(out, " NAME The per-uid name to use\n");
431 dprintf(out, "\n");
432 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
433 dprintf(out, "\n be removed from memory and disk!\n");
434 dprintf(out, "\n");
435 dprintf(out,
Bookatz3e906582018-12-10 17:26:58 -0800436 "usage: adb shell cmd stats dump-report [UID] NAME [--keep_data] "
437 "[--include_current_bucket] [--proto]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700438 dprintf(out, " Dump all metric data for a configuration.\n");
439 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
440 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
441 dprintf(out, " calling uid is used.\n");
442 dprintf(out, " NAME The name of the configuration\n");
Bookatz3e906582018-12-10 17:26:58 -0800443 dprintf(out, " --keep_data Do NOT erase the data upon dumping it.\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700444 dprintf(out, " --proto Print proto binary.\n");
445 dprintf(out, "\n");
446 dprintf(out, "\n");
447 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
448 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
449 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
450 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
451 dprintf(out, " calling uid is used.\n");
452 dprintf(out, " NAME The name of the configuration\n");
453 dprintf(out, "\n");
454 dprintf(out, "\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800455 dprintf(out,
456 "usage: adb shell cmd stats send-active-configs [--uid=UID] [--configs] "
457 "[NAME1] [NAME2] [NAME3..]\n");
458 dprintf(out, " Send a broadcast that informs the subscriber of the current active configs.\n");
459 dprintf(out, " --uid=UID The uid of the configurations. It is only possible to pass\n");
460 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
461 dprintf(out, " calling uid is used.\n");
462 dprintf(out, " --configs Send the list of configs in the name list instead of\n");
463 dprintf(out, " the currently active configs\n");
464 dprintf(out, " NAME LIST List of configuration names to be included in the broadcast.\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800465 dprintf(out, "\n");
466 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700467 dprintf(out, "usage: adb shell cmd stats print-stats\n");
468 dprintf(out, " Prints some basic stats.\n");
469 dprintf(out, " --proto Print proto binary instead of string format.\n");
470 dprintf(out, "\n");
471 dprintf(out, "\n");
472 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
473 dprintf(out, " Clear cached puller data.\n");
474 dprintf(out, "\n");
475 dprintf(out, "usage: adb shell cmd stats print-logs\n");
476 dprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700477}
478
Yao Chena80e5c02018-09-04 13:55:29 -0700479status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800480 string name;
481 bool good = false;
482 int uid;
483 const int argCount = args.size();
484 if (argCount == 2) {
485 // Automatically pick the UID
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800486 uid = AIBinder_getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800487 name.assign(args[1].c_str(), args[1].size());
488 good = true;
489 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800490 good = getUidFromArgs(args, 1, uid);
491 if (!good) {
492 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
493 "other UIDs on eng or userdebug builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800494 }
Bookatzd2386572018-12-14 15:53:14 -0800495 name.assign(args[2].c_str(), args[2].size());
David Chen1d7b0cd2017-11-15 14:20:04 -0800496 }
497 if (!good) {
498 print_cmd_help(out);
499 return UNKNOWN_ERROR;
500 }
David Chend37bc232018-04-12 18:05:11 -0700501 ConfigKey key(uid, StrToInt64(name));
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800502 shared_ptr<IPendingIntentRef> receiver = mConfigManager->GetConfigReceiver(key);
Jeffrey Huangad213742019-12-16 13:50:06 -0800503 if (receiver == nullptr) {
504 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str());
505 return UNKNOWN_ERROR;
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800506 } else if (receiver->sendDataBroadcast(mProcessor->getLastReportTimeNs(key)).isOk()) {
yro74fed972017-11-27 14:42:42 -0800507 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
508 args[2].c_str());
Jeffrey Huangad213742019-12-16 13:50:06 -0800509 } else {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800510 VLOG("StatsService::trigger broadcast failed to %s, %s", args[1].c_str(), args[2].c_str());
Jeffrey Huangad213742019-12-16 13:50:06 -0800511 return UNKNOWN_ERROR;
yro4d889e62017-11-17 15:44:48 -0800512 }
David Chenadaf8b32017-11-03 15:42:08 -0700513 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700514}
515
Tej Singh6ede28b2019-01-29 17:06:54 -0800516status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
517 const int argCount = args.size();
518 int uid;
519 vector<int64_t> configIds;
520 if (argCount == 1) {
521 // Automatically pick the uid and send a broadcast that has no active configs.
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800522 uid = AIBinder_getCallingUid();
Tej Singh6ede28b2019-01-29 17:06:54 -0800523 mProcessor->GetActiveConfigs(uid, configIds);
524 } else {
525 int curArg = 1;
526 if(args[curArg].find("--uid=") == 0) {
527 string uidArgStr(args[curArg].c_str());
528 string uidStr = uidArgStr.substr(6);
529 if (!getUidFromString(uidStr.c_str(), uid)) {
530 dprintf(out, "Invalid UID. Note that the config can only be set for "
531 "other UIDs on eng or userdebug builds.\n");
532 return UNKNOWN_ERROR;
533 }
534 curArg++;
535 } else {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800536 uid = AIBinder_getCallingUid();
Tej Singh6ede28b2019-01-29 17:06:54 -0800537 }
538 if (curArg == argCount || args[curArg] != "--configs") {
539 VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
540 mProcessor->GetActiveConfigs(uid, configIds);
541 } else {
542 // Flag specified, use the given list of configs.
543 curArg++;
544 for (int i = curArg; i < argCount; i++) {
545 char* endp;
546 int64_t configID = strtoll(args[i].c_str(), &endp, 10);
547 if (endp == args[i].c_str() || *endp != '\0') {
548 dprintf(out, "Error parsing config ID.\n");
549 return UNKNOWN_ERROR;
550 }
551 VLOG("Adding config id %ld", static_cast<long>(configID));
552 configIds.push_back(configID);
553 }
554 }
555 }
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800556 shared_ptr<IPendingIntentRef> receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
Jeffrey Huang47537a12020-01-06 15:35:34 -0800557 if (receiver == nullptr) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800558 VLOG("Could not find receiver for uid %d", uid);
Jeffrey Huang47537a12020-01-06 15:35:34 -0800559 return UNKNOWN_ERROR;
560 } else if (receiver->sendActiveConfigsChangedBroadcast(configIds).isOk()) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800561 VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
Jeffrey Huang47537a12020-01-06 15:35:34 -0800562 } else {
563 VLOG("StatsService::trigger active configs changed broadcast failed for uid %d", uid);
564 return UNKNOWN_ERROR;
Tej Singh6ede28b2019-01-29 17:06:54 -0800565 }
566 return NO_ERROR;
567}
568
Yao Chena80e5c02018-09-04 13:55:29 -0700569status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700570 const int argCount = args.size();
571 if (argCount >= 2) {
572 if (args[1] == "update" || args[1] == "remove") {
573 bool good = false;
574 int uid = -1;
575 string name;
576
577 if (argCount == 3) {
578 // Automatically pick the UID
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800579 uid = AIBinder_getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700580 name.assign(args[2].c_str(), args[2].size());
581 good = true;
582 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800583 good = getUidFromArgs(args, 2, uid);
584 if (!good) {
585 dprintf(err, "Invalid UID. Note that the config can only be set for "
586 "other UIDs on eng or userdebug builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700587 }
Bookatzd2386572018-12-14 15:53:14 -0800588 name.assign(args[3].c_str(), args[3].size());
yroe5f82922018-01-22 18:37:27 -0800589 } else if (argCount == 2 && args[1] == "remove") {
590 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700591 }
592
593 if (!good) {
594 // If arg parsing failed, print the help text and return an error.
595 print_cmd_help(out);
596 return UNKNOWN_ERROR;
597 }
598
599 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800600 char* endp;
601 int64_t configID = strtoll(name.c_str(), &endp, 10);
602 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700603 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800604 return UNKNOWN_ERROR;
605 }
606
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700607 // Read stream into buffer.
608 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700609 if (!android::base::ReadFdToString(in, &buffer)) {
610 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700611 return UNKNOWN_ERROR;
612 }
613
614 // Parse buffer.
615 StatsdConfig config;
616 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700617 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700618 return UNKNOWN_ERROR;
619 }
620
621 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800622 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700623 } else {
yro74fed972017-11-27 14:42:42 -0800624 if (argCount == 2) {
625 cmd_remove_all_configs(out);
626 } else {
627 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800628 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800629 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700630 }
631
632 return NO_ERROR;
633 }
David Chen0656b7a2017-09-13 15:53:39 -0700634 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700635 print_cmd_help(out);
636 return UNKNOWN_ERROR;
637}
638
Bookatzff71cad2018-09-20 17:17:49 -0700639status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700640 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800641 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700642 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800643 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700644 bool includeCurrentBucket = false;
Bookatz3e906582018-12-10 17:26:58 -0800645 bool eraseData = true;
Yao Chen729093d2017-10-16 10:33:26 -0700646 int uid;
647 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800648 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
649 proto = true;
650 argCount -= 1;
651 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700652 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
653 includeCurrentBucket = true;
654 argCount -= 1;
655 }
Bookatz3e906582018-12-10 17:26:58 -0800656 if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
657 eraseData = false;
658 argCount -= 1;
659 }
Yao Chen729093d2017-10-16 10:33:26 -0700660 if (argCount == 2) {
661 // Automatically pick the UID
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800662 uid = AIBinder_getCallingUid();
Yao Chen5154a372017-10-30 22:57:06 -0700663 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700664 good = true;
665 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800666 good = getUidFromArgs(args, 1, uid);
667 if (!good) {
668 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
669 "other UIDs on eng or userdebug builds.\n");
Yao Chen729093d2017-10-16 10:33:26 -0700670 }
Bookatzd2386572018-12-14 15:53:14 -0800671 name.assign(args[2].c_str(), args[2].size());
Yao Chen729093d2017-10-16 10:33:26 -0700672 }
673 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800674 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800675 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000676 includeCurrentBucket, eraseData, ADB_DUMP,
677 NO_TIME_CONSTRAINTS,
678 &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800679 if (proto) {
680 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700681 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800682 }
683 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700684 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800685 }
Yao Chen729093d2017-10-16 10:33:26 -0700686 return android::OK;
687 } else {
688 // If arg parsing failed, print the help text and return an error.
689 print_cmd_help(out);
690 return UNKNOWN_ERROR;
691 }
692 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700693 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700694 return UNKNOWN_ERROR;
695 }
696}
697
Yao Chena80e5c02018-09-04 13:55:29 -0700698status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700699 int argCount = args.size();
700 bool proto = false;
701 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
702 proto = true;
703 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800704 }
Yao Chenb3561512017-11-21 18:07:17 -0800705 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700706 if (proto) {
707 vector<uint8_t> data;
708 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
709 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700710 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700711 }
712
713 } else {
714 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
715 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700716 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700717 mProcessor->GetMetricsSize(key));
718 }
719 statsdStats.dumpStats(out);
720 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800721 return NO_ERROR;
722}
723
Yao Chena80e5c02018-09-04 13:55:29 -0700724status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800725 if (args.size() > 1) {
726 string pkg;
727 pkg.assign(args[1].c_str(), args[1].size());
728 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700729 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800730 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700731 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800732 }
Yao Chena80e5c02018-09-04 13:55:29 -0700733 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800734 } else {
735 mUidMap->printUidMap(out);
736 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700737 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700738}
739
Yao Chena80e5c02018-09-04 13:55:29 -0700740status_t StatsService::cmd_write_data_to_disk(int out) {
741 dprintf(out, "Writing data to disk\n");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000742 mProcessor->WriteDataToDisk(ADB_DUMP, NO_TIME_CONSTRAINTS);
yro947fbce2017-11-15 22:50:23 -0800743 return NO_ERROR;
744}
745
Yao Chena80e5c02018-09-04 13:55:29 -0700746status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800747 bool good = false;
748 int32_t uid;
749 int32_t label;
750 int32_t state;
751 const int argCount = args.size();
752 if (argCount == 3) {
753 // Automatically pick the UID
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800754 uid = AIBinder_getCallingUid();
Bookatzb223c4e2018-02-01 15:35:04 -0800755 label = atoi(args[1].c_str());
756 state = atoi(args[2].c_str());
757 good = true;
758 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800759 good = getUidFromArgs(args, 1, uid);
760 if (!good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700761 dprintf(out,
Bookatzd2386572018-12-14 15:53:14 -0800762 "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
763 "done for other UIDs on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800764 }
Bookatzd2386572018-12-14 15:53:14 -0800765 label = atoi(args[2].c_str());
766 state = atoi(args[3].c_str());
Bookatzb223c4e2018-02-01 15:35:04 -0800767 }
768 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700769 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
David Chen0b5c90c2018-01-25 16:51:49 -0800770 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800771 } else {
772 print_cmd_help(out);
773 return UNKNOWN_ERROR;
774 }
775 return NO_ERROR;
776}
777
Tej Singh53f9dee2019-04-30 17:45:54 -0700778status_t StatsService::cmd_log_binary_push(int out, const Vector<String8>& args) {
779 // Security checks are done in the sendBinaryPushStateChanged atom.
780 const int argCount = args.size();
781 if (argCount != 7 && argCount != 8) {
782 dprintf(out, "Incorrect number of argument supplied\n");
783 return UNKNOWN_ERROR;
784 }
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800785 string trainName = string(args[1].c_str());
Tej Singh53f9dee2019-04-30 17:45:54 -0700786 int64_t trainVersion = strtoll(args[2].c_str(), nullptr, 10);
Tej Singh53f9dee2019-04-30 17:45:54 -0700787 int32_t state = atoi(args[6].c_str());
788 vector<int64_t> experimentIds;
789 if (argCount == 8) {
790 vector<string> experimentIdsString = android::base::Split(string(args[7].c_str()), ",");
791 for (string experimentIdString : experimentIdsString) {
792 int64_t experimentId = strtoll(experimentIdString.c_str(), nullptr, 10);
793 experimentIds.push_back(experimentId);
794 }
795 }
796 dprintf(out, "Logging BinaryPushStateChanged\n");
Jonathan Nguyena0e6de12020-01-28 18:33:55 -0800797 vector<uint8_t> experimentIdBytes;
798 writeExperimentIdsToProto(experimentIds, &experimentIdBytes);
799 LogEvent event(trainName, trainVersion, args[3], args[4], args[5], state, experimentIdBytes, 0);
800 mProcessor->OnLogEvent(&event);
Tej Singh53f9dee2019-04-30 17:45:54 -0700801 return NO_ERROR;
802}
803
Yao Chena80e5c02018-09-04 13:55:29 -0700804status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700805 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700806 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800807 if (mPullerManager->Pull(s, &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700808 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700809 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700810 }
Yao Chena80e5c02018-09-04 13:55:29 -0700811 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700812 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700813 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700814 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700815}
816
Yao Chena80e5c02018-09-04 13:55:29 -0700817status_t StatsService::cmd_remove_all_configs(int out) {
818 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800819 VLOG("StatsService::cmd_remove_all_configs was called");
820 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800821 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800822 return NO_ERROR;
823}
824
Yao Chena80e5c02018-09-04 13:55:29 -0700825status_t StatsService::cmd_dump_memory_info(int out) {
826 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800827 return NO_ERROR;
828}
829
Yao Chena80e5c02018-09-04 13:55:29 -0700830status_t StatsService::cmd_clear_puller_cache(int out) {
Yangster-mac932ecec2018-02-01 10:23:52 -0800831 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800832 AIBinder_getCallingPid(), AIBinder_getCallingUid());
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -0800833 if (checkPermission(kPermissionDump)) {
Chenjie Yue2219202018-06-08 10:07:51 -0700834 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700835 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800836 return NO_ERROR;
837 } else {
838 return PERMISSION_DENIED;
839 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800840}
841
Yao Chena80e5c02018-09-04 13:55:29 -0700842status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800843 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", AIBinder_getCallingPid(),
844 AIBinder_getCallingUid());
Ruchir Rastogi0563e3b2020-01-28 17:43:13 -0800845 if (checkPermission(kPermissionDump)) {
Yao Chen876889c2018-05-02 11:16:16 -0700846 bool enabled = true;
847 if (args.size() >= 2) {
848 enabled = atoi(args[1].c_str()) != 0;
849 }
850 mProcessor->setPrintLogs(enabled);
851 return NO_ERROR;
852 } else {
853 return PERMISSION_DENIED;
854 }
855}
856
Bookatzd2386572018-12-14 15:53:14 -0800857bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800858 return getUidFromString(args[uidArgIndex].c_str(), uid);
859}
860
861bool StatsService::getUidFromString(const char* s, int32_t& uid) {
Bookatzd2386572018-12-14 15:53:14 -0800862 if (*s == '\0') {
863 return false;
864 }
865 char* endc = NULL;
866 int64_t longUid = strtol(s, &endc, 0);
867 if (*endc != '\0') {
868 return false;
869 }
870 int32_t goodUid = static_cast<int32_t>(longUid);
871 if (longUid < 0 || static_cast<uint64_t>(longUid) != static_cast<uid_t>(goodUid)) {
872 return false; // It was not of uid_t type.
873 }
874 uid = goodUid;
875
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800876 int32_t callingUid = AIBinder_getCallingUid();
Bookatzd2386572018-12-14 15:53:14 -0800877 return mEngBuild // UserDebug/EngBuild are allowed to impersonate uids.
878 || (callingUid == goodUid) // Anyone can 'impersonate' themselves.
879 || (callingUid == AID_ROOT && goodUid == AID_SHELL); // ROOT can impersonate SHELL.
880}
881
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800882Status StatsService::informAllUidData(const ScopedFileDescriptor& fd) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600883 ENFORCE_UID(AID_SYSTEM);
Max Dashouk11e0d402019-05-16 16:58:07 -0700884 // Read stream into buffer.
885 string buffer;
886 if (!android::base::ReadFdToString(fd.get(), &buffer)) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800887 return exception(EX_ILLEGAL_ARGUMENT, "Failed to read all data from the pipe.");
Max Dashouk11e0d402019-05-16 16:58:07 -0700888 }
Jeff Sharkey6b649252018-04-16 09:50:22 -0600889
Max Dashouk11e0d402019-05-16 16:58:07 -0700890 // Parse buffer.
891 UidData uidData;
892 if (!uidData.ParseFromString(buffer)) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800893 return exception(EX_ILLEGAL_ARGUMENT, "Error parsing proto stream for UidData.");
Max Dashouk11e0d402019-05-16 16:58:07 -0700894 }
David Chende701692017-10-05 13:16:02 -0700895
Max Dashouk11e0d402019-05-16 16:58:07 -0700896 vector<String16> versionStrings;
897 vector<String16> installers;
898 vector<String16> packageNames;
899 vector<int32_t> uids;
900 vector<int64_t> versions;
901
902 const auto numEntries = uidData.app_info_size();
903 versionStrings.reserve(numEntries);
904 installers.reserve(numEntries);
905 packageNames.reserve(numEntries);
906 uids.reserve(numEntries);
907 versions.reserve(numEntries);
908
909 for (const auto& appInfo: uidData.app_info()) {
910 packageNames.emplace_back(String16(appInfo.package_name().c_str()));
911 uids.push_back(appInfo.uid());
912 versions.push_back(appInfo.version());
913 versionStrings.emplace_back(String16(appInfo.version_string().c_str()));
914 installers.emplace_back(String16(appInfo.installer().c_str()));
915 }
916
917 mUidMap->updateMap(getElapsedRealtimeNs(),
918 uids,
919 versions,
920 versionStrings,
921 packageNames,
922 installers);
923
924 VLOG("StatsService::informAllUidData UidData proto parsed successfully.");
David Chende701692017-10-05 13:16:02 -0700925 return Status::ok();
926}
927
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800928Status StatsService::informOnePackage(const string& app, int32_t uid, int64_t version,
929 const string& versionString, const string& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600930 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700931
Jeff Sharkey6b649252018-04-16 09:50:22 -0600932 VLOG("StatsService::informOnePackage was called");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800933 // TODO(b/149254662): This is gross. We should consider changing statsd
934 // internals to use std::string.
935 String16 utf16App = String16(app.c_str());
936 String16 utf16VersionString = String16(versionString.c_str());
937 String16 utf16Installer = String16(installer.c_str());
938
939 mUidMap->updateApp(getElapsedRealtimeNs(), utf16App, uid, version, utf16VersionString,
940 utf16Installer);
David Chende701692017-10-05 13:16:02 -0700941 return Status::ok();
942}
943
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800944Status StatsService::informOnePackageRemoved(const string& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600945 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700946
Jeff Sharkey6b649252018-04-16 09:50:22 -0600947 VLOG("StatsService::informOnePackageRemoved was called");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -0800948 String16 utf16App = String16(app.c_str());
949 mUidMap->removeApp(getElapsedRealtimeNs(), utf16App, uid);
yro01924022018-02-20 18:20:49 -0800950 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -0700951 return Status::ok();
952}
953
Yao Chenef99c4f2017-09-22 16:26:54 -0700954Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600955 ENFORCE_UID(AID_SYSTEM);
956
yro74fed972017-11-27 14:42:42 -0800957 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700958 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800959 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
960 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
961 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -0800962 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -0800963 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -0800964 } else {
965 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
966 }
Bookatz1b0b1142017-09-08 11:58:42 -0700967 return Status::ok();
968}
969
Yangster-mac932ecec2018-02-01 10:23:52 -0800970Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600971 ENFORCE_UID(AID_SYSTEM);
972
Yangster-mac932ecec2018-02-01 10:23:52 -0800973 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700974 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800975 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
976 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
977 if (alarmSet.size() > 0) {
978 VLOG("Found periodic alarm fired.");
979 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
980 } else {
981 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
982 }
983 return Status::ok();
984}
985
Yao Chenef99c4f2017-09-22 16:26:54 -0700986Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600987 ENFORCE_UID(AID_SYSTEM);
988
yro74fed972017-11-27 14:42:42 -0800989 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700990 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -0800991 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700992 return Status::ok();
993}
994
Yao Chenef99c4f2017-09-22 16:26:54 -0700995Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600996 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700997
998 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800999 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -07001000 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001001 return Status::ok();
1002}
1003
Yangster-mac892f3d32018-05-02 14:16:48 -07001004Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001005 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -07001006 VLOG("StatsService::informDeviceShutdown");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001007 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001008 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
yro947fbce2017-11-15 22:50:23 -08001009 return Status::ok();
1010}
1011
Yao Chenef99c4f2017-09-22 16:26:54 -07001012void StatsService::sayHiToStatsCompanion() {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001013 shared_ptr<IStatsCompanionService> statsCompanion = getStatsCompanionService();
Bookatzb487b552017-09-18 11:26:01 -07001014 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -08001015 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -07001016 statsCompanion->statsdReady();
1017 } else {
yro74fed972017-11-27 14:42:42 -08001018 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -07001019 }
1020}
1021
Yao Chenef99c4f2017-09-22 16:26:54 -07001022Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001023 ENFORCE_UID(AID_SYSTEM);
1024
yro74fed972017-11-27 14:42:42 -08001025 VLOG("StatsService::statsCompanionReady was called");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001026 shared_ptr<IStatsCompanionService> statsCompanion = getStatsCompanionService();
Bookatzb487b552017-09-18 11:26:01 -07001027 if (statsCompanion == nullptr) {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001028 return exception(EX_NULL_POINTER,
1029 "StatsCompanion unavailable despite it contacting statsd.");
Bookatzb487b552017-09-18 11:26:01 -07001030 }
yro74fed972017-11-27 14:42:42 -08001031 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001032 AIBinder_linkToDeath(statsCompanion->asBinder().get(),
1033 mStatsCompanionServiceDeathRecipient.get(), this);
Chenjie Yue2219202018-06-08 10:07:51 -07001034 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -08001035 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
1036 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -07001037 return Status::ok();
1038}
1039
Joe Onorato9fc9edf2017-10-15 20:08:52 -07001040void StatsService::Startup() {
1041 mConfigManager->Startup();
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001042 mProcessor->LoadActiveConfigsFromDisk();
Bookatz906a35c2017-09-20 15:26:44 -07001043}
1044
Yangster-mac97e7d202018-10-09 11:05:39 -07001045void StatsService::Terminate() {
1046 ALOGI("StatsService::Terminating");
1047 if (mProcessor != nullptr) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001048 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001049 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
Yangster-mac97e7d202018-10-09 11:05:39 -07001050 }
1051}
1052
Yao Chen0f861862019-03-27 11:51:15 -07001053// Test only interface!!!
Yao Chen3ff3a492018-08-06 16:17:37 -07001054void StatsService::OnLogEvent(LogEvent* event) {
1055 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -07001056 if (mShellSubscriber != nullptr) {
1057 mShellSubscriber->onLogEvent(*event);
1058 }
Bookatz906a35c2017-09-20 15:26:44 -07001059}
1060
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001061Status StatsService::getData(int64_t key, const int32_t callingUid, vector<int8_t>* output) {
Jeffrey Huang04f948b2020-01-07 10:05:25 -08001062 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001063
Jeffrey Huang04f948b2020-01-07 10:05:25 -08001064 VLOG("StatsService::getData with Uid %i", callingUid);
1065 ConfigKey configKey(callingUid, key);
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001066 // TODO(b/149254662): Since libbinder_ndk uses int8_t instead of uint8_t,
1067 // there are inconsistencies with internal statsd logic. Instead of
1068 // modifying lots of files, we create a temporary output array of int8_t and
1069 // copy its data into output. This is a bad hack, but hopefully
1070 // libbinder_ndk will transition to using uint8_t soon: progress is tracked
1071 // in b/144957764. Same applies to StatsService::getMetadata.
1072 vector<uint8_t> unsignedOutput;
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001073 // The dump latency does not matter here since we do not include the current bucket, we do not
1074 // need to pull any new data anyhow.
David Chen56ae0d92018-05-11 16:00:22 -07001075 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001076 true /* erase_data */, GET_DATA_CALLED, FAST, &unsignedOutput);
1077 *output = vector<int8_t>(unsignedOutput.begin(), unsignedOutput.end());
Bookatz4f716292018-04-10 17:15:12 -07001078 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001079}
1080
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001081Status StatsService::getMetadata(vector<int8_t>* output) {
Jeffrey Huang9613a972020-01-07 10:05:03 -08001082 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001083
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001084 vector<uint8_t> unsignedOutput;
1085 StatsdStats::getInstance().dumpStats(&unsignedOutput, false); // Don't reset the counters.
1086 *output = vector<int8_t>(unsignedOutput.begin(), unsignedOutput.end());
Bookatz4f716292018-04-10 17:15:12 -07001087 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -08001088}
1089
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001090Status StatsService::addConfiguration(int64_t key, const vector <int8_t>& config,
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001091 const int32_t callingUid) {
1092 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001093
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001094 if (addConfigurationChecked(callingUid, key, config)) {
David Chen661f7912018-01-22 17:46:24 -08001095 return Status::ok();
1096 } else {
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001097 return exception(EX_ILLEGAL_ARGUMENT, "Could not parse malformatted StatsdConfig.");
David Chen661f7912018-01-22 17:46:24 -08001098 }
1099}
1100
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001101bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<int8_t>& config) {
David Chen9fdd4032018-03-20 14:38:56 -07001102 ConfigKey configKey(uid, key);
1103 StatsdConfig cfg;
1104 if (config.size() > 0) { // If the config is empty, skip parsing.
1105 if (!cfg.ParseFromArray(&config[0], config.size())) {
1106 return false;
1107 }
1108 }
1109 mConfigManager->UpdateConfig(configKey, cfg);
1110 return true;
1111}
1112
Jeffrey Huangad213742019-12-16 13:50:06 -08001113Status StatsService::removeDataFetchOperation(int64_t key,
1114 const int32_t callingUid) {
1115 ENFORCE_UID(AID_SYSTEM);
1116 ConfigKey configKey(callingUid, key);
Bookatz4f716292018-04-10 17:15:12 -07001117 mConfigManager->RemoveConfigReceiver(configKey);
1118 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -08001119}
1120
Jeff Sharkey6b649252018-04-16 09:50:22 -06001121Status StatsService::setDataFetchOperation(int64_t key,
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001122 const shared_ptr<IPendingIntentRef>& pir,
Jeffrey Huangad213742019-12-16 13:50:06 -08001123 const int32_t callingUid) {
1124 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001125
Jeffrey Huangad213742019-12-16 13:50:06 -08001126 ConfigKey configKey(callingUid, key);
1127 mConfigManager->SetConfigReceiver(configKey, pir);
David Chen48944902018-05-03 10:29:11 -07001128 if (StorageManager::hasConfigMetricsReport(configKey)) {
1129 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
1130 configKey.ToString().c_str());
1131 mProcessor->noteOnDiskData(configKey);
1132 }
Bookatz4f716292018-04-10 17:15:12 -07001133 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001134}
1135
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001136Status StatsService::setActiveConfigsChangedOperation(const shared_ptr<IPendingIntentRef>& pir,
Jeffrey Huang47537a12020-01-06 15:35:34 -08001137 const int32_t callingUid,
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001138 vector<int64_t>* output) {
Jeffrey Huang47537a12020-01-06 15:35:34 -08001139 ENFORCE_UID(AID_SYSTEM);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001140
Jeffrey Huang47537a12020-01-06 15:35:34 -08001141 mConfigManager->SetActiveConfigsChangedReceiver(callingUid, pir);
Tej Singh6ede28b2019-01-29 17:06:54 -08001142 if (output != nullptr) {
Jeffrey Huang47537a12020-01-06 15:35:34 -08001143 mProcessor->GetActiveConfigs(callingUid, *output);
Tej Singh6ede28b2019-01-29 17:06:54 -08001144 } else {
1145 ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
1146 }
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001147 return Status::ok();
1148}
1149
Jeffrey Huang47537a12020-01-06 15:35:34 -08001150Status StatsService::removeActiveConfigsChangedOperation(const int32_t callingUid) {
1151 ENFORCE_UID(AID_SYSTEM);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001152
Jeffrey Huang47537a12020-01-06 15:35:34 -08001153 mConfigManager->RemoveActiveConfigsChangedReceiver(callingUid);
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001154 return Status::ok();
1155}
1156
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001157Status StatsService::removeConfiguration(int64_t key, const int32_t callingUid) {
1158 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001159
Jeffrey Huang94eafe72020-01-07 15:18:43 -08001160 ConfigKey configKey(callingUid, key);
Bookatz4f716292018-04-10 17:15:12 -07001161 mConfigManager->RemoveConfig(configKey);
Bookatz4f716292018-04-10 17:15:12 -07001162 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001163}
1164
Bookatzc6977972018-01-16 16:55:05 -08001165Status StatsService::setBroadcastSubscriber(int64_t configId,
1166 int64_t subscriberId,
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001167 const shared_ptr<IPendingIntentRef>& pir,
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001168 const int32_t callingUid) {
1169 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001170
Bookatzc6977972018-01-16 16:55:05 -08001171 VLOG("StatsService::setBroadcastSubscriber called.");
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001172 ConfigKey configKey(callingUid, configId);
Bookatz4f716292018-04-10 17:15:12 -07001173 SubscriberReporter::getInstance()
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001174 .setBroadcastSubscriber(configKey, subscriberId, pir);
Bookatz4f716292018-04-10 17:15:12 -07001175 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001176}
1177
1178Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001179 int64_t subscriberId,
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001180 const int32_t callingUid) {
1181 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001182
Bookatzc6977972018-01-16 16:55:05 -08001183 VLOG("StatsService::unsetBroadcastSubscriber called.");
Jeffrey Huang4f2e6bd2020-01-06 16:24:45 -08001184 ConfigKey configKey(callingUid, configId);
Bookatz4f716292018-04-10 17:15:12 -07001185 SubscriberReporter::getInstance()
1186 .unsetBroadcastSubscriber(configKey, subscriberId);
1187 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001188}
1189
yrobe6d7f92018-05-04 13:02:53 -07001190Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
1191 // Permission check not necessary as it's meant for applications to write to
1192 // statsd.
1193 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001194 (int32_t) AIBinder_getCallingUid(), label,
yrobe6d7f92018-05-04 13:02:53 -07001195 state);
1196 return Status::ok();
1197}
1198
Tej Singh72a70a82020-02-26 23:46:29 -08001199Status StatsService::registerPullAtomCallback(int32_t uid, int32_t atomTag, int64_t coolDownMillis,
1200 int64_t timeoutMillis,
1201 const std::vector<int32_t>& additiveFields,
1202 const shared_ptr<IPullAtomCallback>& pullerCallback) {
Tej Singh6a5c9432019-10-11 11:07:06 -07001203 ENFORCE_UID(AID_SYSTEM);
Tej Singhb7802512019-12-04 17:57:04 -08001204 VLOG("StatsService::registerPullAtomCallback called.");
Tej Singh72a70a82020-02-26 23:46:29 -08001205 mPullerManager->RegisterPullAtomCallback(uid, atomTag, MillisToNano(coolDownMillis),
1206 MillisToNano(timeoutMillis), additiveFields,
Tej Singhb7802512019-12-04 17:57:04 -08001207 pullerCallback);
1208 return Status::ok();
1209}
1210
1211Status StatsService::registerNativePullAtomCallback(int32_t atomTag, int64_t coolDownNs,
1212 int64_t timeoutNs, const std::vector<int32_t>& additiveFields,
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001213 const shared_ptr<IPullAtomCallback>& pullerCallback) {
Tej Singhb7802512019-12-04 17:57:04 -08001214
1215 VLOG("StatsService::registerNativePullAtomCallback called.");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001216 int32_t uid = AIBinder_getCallingUid();
Tej Singh6a5c9432019-10-11 11:07:06 -07001217 mPullerManager->RegisterPullAtomCallback(uid, atomTag, coolDownNs, timeoutNs, additiveFields,
1218 pullerCallback);
Tej Singh59184292019-10-11 11:07:06 -07001219 return Status::ok();
1220}
1221
Tej Singhfa1c1372019-12-05 20:36:54 -08001222Status StatsService::unregisterPullAtomCallback(int32_t uid, int32_t atomTag) {
1223 ENFORCE_UID(AID_SYSTEM);
1224 VLOG("StatsService::unregisterPullAtomCallback called.");
1225 mPullerManager->UnregisterPullAtomCallback(uid, atomTag);
1226 return Status::ok();
1227}
1228
Tej Singh8f358602020-01-15 16:05:39 -08001229Status StatsService::unregisterNativePullAtomCallback(int32_t atomTag) {
1230 VLOG("StatsService::unregisterNativePullAtomCallback called.");
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001231 int32_t uid = AIBinder_getCallingUid();
Tej Singh8f358602020-01-15 16:05:39 -08001232 mPullerManager->UnregisterPullAtomCallback(uid, atomTag);
1233 return Status::ok();
1234}
1235
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001236Status StatsService::getRegisteredExperimentIds(std::vector<int64_t>* experimentIdsOut) {
Jeffrey Huang80c9a972020-01-07 10:04:27 -08001237 ENFORCE_UID(AID_SYSTEM);
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001238 // TODO: add verifier permission
1239
Jonathan Nguyen703c42f2020-02-04 15:54:26 -08001240 experimentIdsOut->clear();
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001241 // Read the latest train info
Jonathan Nguyen703c42f2020-02-04 15:54:26 -08001242 vector<InstallTrainInfo> trainInfoList = StorageManager::readAllTrainInfo();
1243 if (trainInfoList.empty()) {
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001244 // No train info means no experiment IDs, return an empty list
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001245 return Status::ok();
1246 }
1247
1248 // Copy the experiment IDs to the out vector
Jonathan Nguyen703c42f2020-02-04 15:54:26 -08001249 for (InstallTrainInfo& trainInfo : trainInfoList) {
1250 experimentIdsOut->insert(experimentIdsOut->end(),
1251 trainInfo.experimentIds.begin(),
1252 trainInfo.experimentIds.end());
1253 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001254 return Status::ok();
1255}
1256
Ruchir Rastogie449b0c2020-02-10 17:40:09 -08001257
1258void StatsService::statsCompanionServiceDied(void* cookie) {
1259 auto thiz = static_cast<StatsService*>(cookie);
1260 thiz->statsCompanionServiceDiedImpl();
1261}
1262
1263void StatsService::statsCompanionServiceDiedImpl() {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001264 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001265 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1266 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001267 ALOGW("Reset statsd upon system server restarts.");
Tej Singhf53d4452019-05-09 18:17:59 -07001268 int64_t systemServerRestartNs = getElapsedRealtimeNs();
1269 ProtoOutputStream proto;
1270 mProcessor->WriteActiveConfigsToProtoOutputStream(systemServerRestartNs,
1271 STATSCOMPANION_DIED, &proto);
1272
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001273 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED, FAST);
Yangster-mac892f3d32018-05-02 14:16:48 -07001274 mProcessor->resetConfigs();
Tej Singhf53d4452019-05-09 18:17:59 -07001275
1276 std::string serializedActiveConfigs;
1277 if (proto.serializeToString(&serializedActiveConfigs)) {
1278 ActiveConfigList activeConfigs;
1279 if (activeConfigs.ParseFromString(serializedActiveConfigs)) {
1280 mProcessor->SetConfigsActiveState(activeConfigs, systemServerRestartNs);
1281 }
1282 }
Yangster-mac892f3d32018-05-02 14:16:48 -07001283 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001284 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1285 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001286 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001287}
1288
Yao Chenef99c4f2017-09-22 16:26:54 -07001289} // namespace statsd
1290} // namespace os
1291} // namespace android