blob: 52ecdc8425af43c21f30ef4fcec750bcbb4a0d22 [file] [log] [blame]
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001/*
yro0feae942017-11-15 14:38:48 -08002 * Copyright (C) 2017 The Android Open Source Project
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07003 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Tej Singh484524a2018-02-01 15:10:05 -080017#define DEBUG false // STOPSHIP if true
Joe Onorato9fc9edf2017-10-15 20:08:52 -070018#include "Log.h"
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070019
20#include "StatsService.h"
Yangster-mac330af582018-02-08 15:24:38 -080021#include "stats_log_util.h"
Yao Chen8d9989b2017-11-18 18:54:50 -080022#include "android-base/stringprintf.h"
David Chenadaf8b32017-11-03 15:42:08 -070023#include "config/ConfigKey.h"
24#include "config/ConfigManager.h"
Yao Chenb3561512017-11-21 18:07:17 -080025#include "guardrail/StatsdStats.h"
yro947fbce2017-11-15 22:50:23 -080026#include "storage/StorageManager.h"
Bookatzc6977972018-01-16 16:55:05 -080027#include "subscriber/SubscriberReporter.h"
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070028
David Chen0656b7a2017-09-13 15:53:39 -070029#include <android-base/file.h>
Jeff Sharkey6b649252018-04-16 09:50:22 -060030#include <android-base/stringprintf.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070031#include <binder/IPCThreadState.h>
32#include <binder/IServiceManager.h>
Jeff Sharkey6b649252018-04-16 09:50:22 -060033#include <binder/PermissionController.h>
Chenjie Yu6b1667c2019-01-18 10:09:33 -080034#include <cutils/multiuser.h>
yro87d983c2017-11-14 21:31:43 -080035#include <dirent.h>
David Chen0656b7a2017-09-13 15:53:39 -070036#include <frameworks/base/cmds/statsd/src/statsd_config.pb.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070037#include <private/android_filesystem_config.h>
Bookatzb223c4e2018-02-01 15:35:04 -080038#include <statslog.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070039#include <stdio.h>
Yao Chen482d2722017-09-12 13:25:43 -070040#include <stdlib.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070041#include <sys/system_properties.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070042#include <unistd.h>
Yao Chena80e5c02018-09-04 13:55:29 -070043#include <utils/Looper.h>
44#include <utils/String16.h>
45#include <chrono>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070046
47using namespace android;
48
Jeff Sharkey6b649252018-04-16 09:50:22 -060049using android::base::StringPrintf;
Bookatzff71cad2018-09-20 17:17:49 -070050using android::util::FIELD_COUNT_REPEATED;
Chenjie Yu6b1667c2019-01-18 10:09:33 -080051using android::util::FIELD_TYPE_INT64;
Bookatzff71cad2018-09-20 17:17:49 -070052using android::util::FIELD_TYPE_MESSAGE;
Joe Onorato99598ee2019-02-11 15:55:13 +000053using android::util::ProtoReader;
Jeff Sharkey6b649252018-04-16 09:50:22 -060054
Bookatz906a35c2017-09-20 15:26:44 -070055namespace android {
56namespace os {
57namespace statsd {
58
David Chenadaf8b32017-11-03 15:42:08 -070059constexpr const char* kPermissionDump = "android.permission.DUMP";
Jeff Sharkey6b649252018-04-16 09:50:22 -060060constexpr const char* kPermissionUsage = "android.permission.PACKAGE_USAGE_STATS";
61
62constexpr const char* kOpUsage = "android:get_usage_stats";
63
yro03faf092017-12-12 00:17:50 -080064#define STATS_SERVICE_DIR "/data/misc/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070065
Bookatzff71cad2018-09-20 17:17:49 -070066// for StatsDataDumpProto
67const int FIELD_ID_REPORTS_LIST = 1;
Chenjie Yu97dbb202019-02-13 16:42:04 -080068// for TrainInfo experiment id serialization
69const int FIELD_ID_EXPERIMENT_ID = 1;
Bookatzff71cad2018-09-20 17:17:49 -070070
Jeff Sharkey6b649252018-04-16 09:50:22 -060071static binder::Status ok() {
72 return binder::Status::ok();
73}
74
75static binder::Status exception(uint32_t code, const std::string& msg) {
76 ALOGE("%s (%d)", msg.c_str(), code);
77 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
78}
79
80binder::Status checkUid(uid_t expectedUid) {
81 uid_t uid = IPCThreadState::self()->getCallingUid();
82 if (uid == expectedUid || uid == AID_ROOT) {
83 return ok();
84 } else {
85 return exception(binder::Status::EX_SECURITY,
86 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
87 }
88}
89
90binder::Status checkDumpAndUsageStats(const String16& packageName) {
91 pid_t pid = IPCThreadState::self()->getCallingPid();
92 uid_t uid = IPCThreadState::self()->getCallingUid();
93
94 // Root, system, and shell always have access
95 if (uid == AID_ROOT || uid == AID_SYSTEM || uid == AID_SHELL) {
96 return ok();
97 }
98
99 // Caller must be granted these permissions
100 if (!checkCallingPermission(String16(kPermissionDump))) {
101 return exception(binder::Status::EX_SECURITY,
102 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionDump));
103 }
104 if (!checkCallingPermission(String16(kPermissionUsage))) {
105 return exception(binder::Status::EX_SECURITY,
106 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionUsage));
107 }
108
109 // Caller must also have usage stats op granted
110 PermissionController pc;
111 switch (pc.noteOp(String16(kOpUsage), uid, packageName)) {
112 case PermissionController::MODE_ALLOWED:
113 case PermissionController::MODE_DEFAULT:
114 return ok();
115 default:
116 return exception(binder::Status::EX_SECURITY,
117 StringPrintf("UID %d / PID %d lacks app-op %s", uid, pid, kOpUsage));
118 }
119}
120
121#define ENFORCE_UID(uid) { \
122 binder::Status status = checkUid((uid)); \
123 if (!status.isOk()) { \
124 return status; \
125 } \
126}
127
128#define ENFORCE_DUMP_AND_USAGE_STATS(packageName) { \
129 binder::Status status = checkDumpAndUsageStats(packageName); \
130 if (!status.isOk()) { \
131 return status; \
132 } \
133}
134
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700135StatsService::StatsService(const sp<Looper>& handlerLooper)
Yangster-mac932ecec2018-02-01 10:23:52 -0800136 : mAnomalyAlarmMonitor(new AlarmMonitor(MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
137 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
138 if (sc != nullptr) {
139 sc->setAnomalyAlarm(timeMillis);
140 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
141 }
142 },
143 [](const sp<IStatsCompanionService>& sc) {
144 if (sc != nullptr) {
145 sc->cancelAnomalyAlarm();
146 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
147 }
148 })),
149 mPeriodicAlarmMonitor(new AlarmMonitor(MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
150 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
151 if (sc != nullptr) {
152 sc->setAlarmForSubscriberTriggering(timeMillis);
153 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
154 }
155 },
156 [](const sp<IStatsCompanionService>& sc) {
157 if (sc != nullptr) {
158 sc->cancelAlarmForSubscriberTriggering();
159 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
160 }
161
162 })) {
Yao Chen4ce07292019-02-13 13:06:36 -0800163 mUidMap = UidMap::getInstance();
Chenjie Yue2219202018-06-08 10:07:51 -0700164 mPullerManager = new StatsPullerManager();
Chenjie Yu80f91122018-01-31 20:24:50 -0800165 StatsPuller::SetUidMap(mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700166 mConfigManager = new ConfigManager();
Chenjie Yue2219202018-06-08 10:07:51 -0700167 mProcessor = new StatsLogProcessor(
168 mUidMap, mPullerManager, mAnomalyAlarmMonitor, mPeriodicAlarmMonitor,
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800169 getElapsedRealtimeNs(),
170 [this](const ConfigKey& key) {
Chenjie Yue2219202018-06-08 10:07:51 -0700171 sp<IStatsCompanionService> sc = getStatsCompanionService();
172 auto receiver = mConfigManager->GetConfigReceiver(key);
173 if (sc == nullptr) {
174 VLOG("Could not find StatsCompanionService");
175 return false;
176 } else if (receiver == nullptr) {
177 VLOG("Statscompanion could not find a broadcast receiver for %s",
178 key.ToString().c_str());
179 return false;
180 } else {
181 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
182 return true;
183 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800184 },
185 [this](const int& uid, const vector<int64_t>& activeConfigs) {
186 auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
187 sp<IStatsCompanionService> sc = getStatsCompanionService();
188 if (sc == nullptr) {
189 VLOG("Could not access statsCompanion");
190 return false;
191 } else if (receiver == nullptr) {
192 VLOG("Could not find receiver for uid %d", uid);
193 return false;
194 } else {
195 sc->sendActiveConfigsChangedBroadcast(receiver, activeConfigs);
196 VLOG("StatsService::active configs broadcast succeeded for uid %d" , uid);
197 return true;
198 }
Chenjie Yue2219202018-06-08 10:07:51 -0700199 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700200
201 mConfigManager->AddListener(mProcessor);
202
203 init_system_properties();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700204}
205
Yao Chenef99c4f2017-09-22 16:26:54 -0700206StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700207}
208
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700209void StatsService::init_system_properties() {
210 mEngBuild = false;
211 const prop_info* buildType = __system_property_find("ro.build.type");
212 if (buildType != NULL) {
213 __system_property_read_callback(buildType, init_build_type_callback, this);
214 }
David Chen0656b7a2017-09-13 15:53:39 -0700215}
216
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700217void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
218 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700219 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700220 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
221 }
222}
223
224/**
225 * Implement our own because the default binder implementation isn't
226 * properly handling SHELL_COMMAND_TRANSACTION.
227 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700228status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
229 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700230 switch (code) {
231 case SHELL_COMMAND_TRANSACTION: {
232 int in = data.readFileDescriptor();
233 int out = data.readFileDescriptor();
234 int err = data.readFileDescriptor();
235 int argc = data.readInt32();
236 Vector<String8> args;
237 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
238 args.add(String8(data.readString16()));
239 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700240 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
241 sp<IResultReceiver> resultReceiver =
242 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700243
Yao Chena80e5c02018-09-04 13:55:29 -0700244 err = command(in, out, err, args, resultReceiver);
245 resultReceiver->send(err);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700246 return NO_ERROR;
247 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700248 default: { return BnStatsManager::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700249 }
250}
251
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700252/**
Bookatzff71cad2018-09-20 17:17:49 -0700253 * Write data from statsd.
254 * Format for statsdStats: adb shell dumpsys stats --metadata [-v] [--proto]
255 * Format for data report: adb shell dumpsys stats [anything other than --metadata] [--proto]
256 * Anything ending in --proto will be in proto format.
257 * Anything without --metadata as the first argument will be report information.
258 * (bugreports call "adb shell dumpsys stats --dump-priority NORMAL -a --proto")
259 * TODO: Come up with a more robust method of enacting <serviceutils/PriorityDumper.h>.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700260 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700261status_t StatsService::dump(int fd, const Vector<String16>& args) {
Tej Singhdd83d702018-04-10 17:24:50 -0700262 if (!checkCallingPermission(String16(kPermissionDump))) {
263 return PERMISSION_DENIED;
264 }
Bookatzff71cad2018-09-20 17:17:49 -0700265 int lastArg = args.size() - 1;
266 bool asProto = false;
267 if (lastArg >= 0 && !args[lastArg].compare(String16("--proto"))) { // last argument
268 asProto = true;
269 lastArg--;
Yao Chen884c8c12018-01-26 10:36:25 -0800270 }
Bookatzff71cad2018-09-20 17:17:49 -0700271 if (args.size() > 0 && !args[0].compare(String16("--metadata"))) { // first argument
272 // Request is to dump statsd stats.
273 bool verbose = false;
274 if (lastArg >= 0 && !args[lastArg].compare(String16("-v"))) {
275 verbose = true;
276 lastArg--;
277 }
278 dumpStatsdStats(fd, verbose, asProto);
279 } else {
280 // Request is to dump statsd report data.
281 if (asProto) {
282 dumpIncidentSection(fd);
283 } else {
284 dprintf(fd, "Non-proto format of stats data dump not available; see proto version.\n");
285 }
Tej Singh41b3f9a2018-04-03 17:06:35 -0700286 }
Yao Chen884c8c12018-01-26 10:36:25 -0800287
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700288 return NO_ERROR;
289}
290
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700291/**
Tej Singh41b3f9a2018-04-03 17:06:35 -0700292 * Write debugging data about statsd in text or proto format.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700293 */
Bookatzff71cad2018-09-20 17:17:49 -0700294void StatsService::dumpStatsdStats(int out, bool verbose, bool proto) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700295 if (proto) {
296 vector<uint8_t> data;
297 StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
298 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700299 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700300 }
301 } else {
302 StatsdStats::getInstance().dumpStats(out);
303 mProcessor->dumpStates(out, verbose);
304 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700305}
306
307/**
Bookatzff71cad2018-09-20 17:17:49 -0700308 * Write stats report data in StatsDataDumpProto incident section format.
309 */
310void StatsService::dumpIncidentSection(int out) {
311 ProtoOutputStream proto;
312 for (const ConfigKey& configKey : mConfigManager->GetAllConfigKeys()) {
313 uint64_t reportsListToken =
314 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS_LIST);
315 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
316 true /* includeCurrentBucket */, false /* erase_data */,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000317 ADB_DUMP,
318 FAST,
319 &proto);
Bookatzff71cad2018-09-20 17:17:49 -0700320 proto.end(reportsListToken);
321 proto.flush(out);
Bookatzc71d9012018-12-19 12:28:38 -0800322 proto.clear();
Bookatzff71cad2018-09-20 17:17:49 -0700323 }
324}
325
326/**
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700327 * Implementation of the adb shell cmd stats command.
328 */
Yao Chena80e5c02018-09-04 13:55:29 -0700329status_t StatsService::command(int in, int out, int err, Vector<String8>& args,
330 sp<IResultReceiver> resultReceiver) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600331 uid_t uid = IPCThreadState::self()->getCallingUid();
332 if (uid != AID_ROOT && uid != AID_SHELL) {
333 return PERMISSION_DENIED;
334 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700335
336 const int argCount = args.size();
337 if (argCount >= 1) {
338 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700339 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700340 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700341 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700342
David Chende701692017-10-05 13:16:02 -0700343 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800344 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700345 }
Yao Chen729093d2017-10-16 10:33:26 -0700346
347 if (!args[0].compare(String8("dump-report"))) {
Bookatzff71cad2018-09-20 17:17:49 -0700348 return cmd_dump_report(out, args);
Yao Chen729093d2017-10-16 10:33:26 -0700349 }
David Chen1481fe12017-10-16 13:16:34 -0700350
351 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
352 return cmd_print_pulled_metrics(out, args);
353 }
David Chenadaf8b32017-11-03 15:42:08 -0700354
355 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800356 return cmd_trigger_broadcast(out, args);
357 }
358
359 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800360 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700361 }
yro87d983c2017-11-14 21:31:43 -0800362
Yao Chen8d9989b2017-11-18 18:54:50 -0800363 if (!args[0].compare(String8("meminfo"))) {
364 return cmd_dump_memory_info(out);
365 }
yro947fbce2017-11-15 22:50:23 -0800366
367 if (!args[0].compare(String8("write-to-disk"))) {
368 return cmd_write_data_to_disk(out);
369 }
Bookatzb223c4e2018-02-01 15:35:04 -0800370
David Chen0b5c90c2018-01-25 16:51:49 -0800371 if (!args[0].compare(String8("log-app-breadcrumb"))) {
372 return cmd_log_app_breadcrumb(out, args);
Bookatzb223c4e2018-02-01 15:35:04 -0800373 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800374
375 if (!args[0].compare(String8("clear-puller-cache"))) {
376 return cmd_clear_puller_cache(out);
377 }
Yao Chen876889c2018-05-02 11:16:16 -0700378
379 if (!args[0].compare(String8("print-logs"))) {
380 return cmd_print_logs(out, args);
381 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800382 if (!args[0].compare(String8("send-active-configs"))) {
383 return cmd_trigger_active_config_broadcast(out, args);
384 }
Yao Chena80e5c02018-09-04 13:55:29 -0700385 if (!args[0].compare(String8("data-subscribe"))) {
386 if (mShellSubscriber == nullptr) {
Yao Chen41e606c2018-10-05 15:54:11 -0700387 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
Yao Chena80e5c02018-09-04 13:55:29 -0700388 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800389 int timeoutSec = -1;
390 if (argCount >= 2) {
391 timeoutSec = atoi(args[1].c_str());
392 }
393 mShellSubscriber->startNewSubscription(in, out, resultReceiver, timeoutSec);
Yao Chena80e5c02018-09-04 13:55:29 -0700394 return NO_ERROR;
395 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700396 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700397
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700398 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700399 return NO_ERROR;
400}
401
Yao Chena80e5c02018-09-04 13:55:29 -0700402void StatsService::print_cmd_help(int out) {
403 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700404 "usage: adb shell cmd stats print-stats-log [tag_required] "
405 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700406 dprintf(out, "\n");
407 dprintf(out, "\n");
408 dprintf(out, "usage: adb shell cmd stats meminfo\n");
409 dprintf(out, "\n");
410 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
411 dprintf(out, " # adb shell stop\n");
412 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
413 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
414 dprintf(out, " # adb shell start\n");
415 dprintf(out, "\n");
416 dprintf(out, "\n");
417 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
418 dprintf(out, "\n");
419 dprintf(out, " Prints the UID, app name, version mapping.\n");
420 dprintf(out, " PKG Optional package name to print the uids of the package\n");
421 dprintf(out, "\n");
422 dprintf(out, "\n");
423 dprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
424 dprintf(out, "\n");
425 dprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
426 dprintf(out, "\n");
427 dprintf(out, "\n");
428 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
429 dprintf(out, "\n");
430 dprintf(out, " Flushes all data on memory to disk.\n");
431 dprintf(out, "\n");
432 dprintf(out, "\n");
433 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
434 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
435 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
436 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
437 dprintf(out, " uid is used.\n");
438 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
439 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
440 dprintf(out, "\n");
441 dprintf(out, "\n");
442 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
443 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
444 dprintf(out, "\n");
445 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
446 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
447 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
448 dprintf(out, "\n");
449 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
450 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
451 dprintf(out, " uid is used.\n");
452 dprintf(out, " NAME The per-uid name to use\n");
453 dprintf(out, "\n");
454 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
455 dprintf(out, "\n be removed from memory and disk!\n");
456 dprintf(out, "\n");
457 dprintf(out,
Bookatz3e906582018-12-10 17:26:58 -0800458 "usage: adb shell cmd stats dump-report [UID] NAME [--keep_data] "
459 "[--include_current_bucket] [--proto]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700460 dprintf(out, " Dump all metric data for a configuration.\n");
461 dprintf(out, " UID The uid of the configuration. 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, " NAME The name of the configuration\n");
Bookatz3e906582018-12-10 17:26:58 -0800465 dprintf(out, " --keep_data Do NOT erase the data upon dumping it.\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700466 dprintf(out, " --proto Print proto binary.\n");
467 dprintf(out, "\n");
468 dprintf(out, "\n");
469 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
470 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
471 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
472 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
473 dprintf(out, " calling uid is used.\n");
474 dprintf(out, " NAME The name of the configuration\n");
475 dprintf(out, "\n");
476 dprintf(out, "\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800477 dprintf(out,
478 "usage: adb shell cmd stats send-active-configs [--uid=UID] [--configs] "
479 "[NAME1] [NAME2] [NAME3..]\n");
480 dprintf(out, " Send a broadcast that informs the subscriber of the current active configs.\n");
481 dprintf(out, " --uid=UID The uid of the configurations. It is only possible to pass\n");
482 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
483 dprintf(out, " calling uid is used.\n");
484 dprintf(out, " --configs Send the list of configs in the name list instead of\n");
485 dprintf(out, " the currently active configs\n");
486 dprintf(out, " NAME LIST List of configuration names to be included in the broadcast.\n");
487
488 dprintf(out, "\n");
489 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700490 dprintf(out, "usage: adb shell cmd stats print-stats\n");
491 dprintf(out, " Prints some basic stats.\n");
492 dprintf(out, " --proto Print proto binary instead of string format.\n");
493 dprintf(out, "\n");
494 dprintf(out, "\n");
495 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
496 dprintf(out, " Clear cached puller data.\n");
497 dprintf(out, "\n");
498 dprintf(out, "usage: adb shell cmd stats print-logs\n");
499 dprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700500}
501
Yao Chena80e5c02018-09-04 13:55:29 -0700502status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800503 string name;
504 bool good = false;
505 int uid;
506 const int argCount = args.size();
507 if (argCount == 2) {
508 // Automatically pick the UID
509 uid = IPCThreadState::self()->getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800510 name.assign(args[1].c_str(), args[1].size());
511 good = true;
512 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800513 good = getUidFromArgs(args, 1, uid);
514 if (!good) {
515 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
516 "other UIDs on eng or userdebug builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800517 }
Bookatzd2386572018-12-14 15:53:14 -0800518 name.assign(args[2].c_str(), args[2].size());
David Chen1d7b0cd2017-11-15 14:20:04 -0800519 }
520 if (!good) {
521 print_cmd_help(out);
522 return UNKNOWN_ERROR;
523 }
David Chend37bc232018-04-12 18:05:11 -0700524 ConfigKey key(uid, StrToInt64(name));
525 auto receiver = mConfigManager->GetConfigReceiver(key);
yro4d889e62017-11-17 15:44:48 -0800526 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen661f7912018-01-22 17:46:24 -0800527 if (sc == nullptr) {
528 VLOG("Could not access statsCompanion");
529 } else if (receiver == nullptr) {
530 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str())
531 } else {
David Chend37bc232018-04-12 18:05:11 -0700532 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
yro74fed972017-11-27 14:42:42 -0800533 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
534 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800535 }
536
David Chenadaf8b32017-11-03 15:42:08 -0700537 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700538}
539
Tej Singh6ede28b2019-01-29 17:06:54 -0800540status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
541 const int argCount = args.size();
542 int uid;
543 vector<int64_t> configIds;
544 if (argCount == 1) {
545 // Automatically pick the uid and send a broadcast that has no active configs.
546 uid = IPCThreadState::self()->getCallingUid();
547 mProcessor->GetActiveConfigs(uid, configIds);
548 } else {
549 int curArg = 1;
550 if(args[curArg].find("--uid=") == 0) {
551 string uidArgStr(args[curArg].c_str());
552 string uidStr = uidArgStr.substr(6);
553 if (!getUidFromString(uidStr.c_str(), uid)) {
554 dprintf(out, "Invalid UID. Note that the config can only be set for "
555 "other UIDs on eng or userdebug builds.\n");
556 return UNKNOWN_ERROR;
557 }
558 curArg++;
559 } else {
560 uid = IPCThreadState::self()->getCallingUid();
561 }
562 if (curArg == argCount || args[curArg] != "--configs") {
563 VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
564 mProcessor->GetActiveConfigs(uid, configIds);
565 } else {
566 // Flag specified, use the given list of configs.
567 curArg++;
568 for (int i = curArg; i < argCount; i++) {
569 char* endp;
570 int64_t configID = strtoll(args[i].c_str(), &endp, 10);
571 if (endp == args[i].c_str() || *endp != '\0') {
572 dprintf(out, "Error parsing config ID.\n");
573 return UNKNOWN_ERROR;
574 }
575 VLOG("Adding config id %ld", static_cast<long>(configID));
576 configIds.push_back(configID);
577 }
578 }
579 }
580 auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
581 sp<IStatsCompanionService> sc = getStatsCompanionService();
582 if (sc == nullptr) {
583 VLOG("Could not access statsCompanion");
584 } else if (receiver == nullptr) {
585 VLOG("Could not find receiver for uid %d", uid);
586 } else {
587 sc->sendActiveConfigsChangedBroadcast(receiver, configIds);
588 VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
589 }
590 return NO_ERROR;
591}
592
Yao Chena80e5c02018-09-04 13:55:29 -0700593status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700594 const int argCount = args.size();
595 if (argCount >= 2) {
596 if (args[1] == "update" || args[1] == "remove") {
597 bool good = false;
598 int uid = -1;
599 string name;
600
601 if (argCount == 3) {
602 // Automatically pick the UID
603 uid = IPCThreadState::self()->getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700604 name.assign(args[2].c_str(), args[2].size());
605 good = true;
606 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800607 good = getUidFromArgs(args, 2, uid);
608 if (!good) {
609 dprintf(err, "Invalid UID. Note that the config can only be set for "
610 "other UIDs on eng or userdebug builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700611 }
Bookatzd2386572018-12-14 15:53:14 -0800612 name.assign(args[3].c_str(), args[3].size());
yroe5f82922018-01-22 18:37:27 -0800613 } else if (argCount == 2 && args[1] == "remove") {
614 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700615 }
616
617 if (!good) {
618 // If arg parsing failed, print the help text and return an error.
619 print_cmd_help(out);
620 return UNKNOWN_ERROR;
621 }
622
623 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800624 char* endp;
625 int64_t configID = strtoll(name.c_str(), &endp, 10);
626 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700627 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800628 return UNKNOWN_ERROR;
629 }
630
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700631 // Read stream into buffer.
632 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700633 if (!android::base::ReadFdToString(in, &buffer)) {
634 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700635 return UNKNOWN_ERROR;
636 }
637
638 // Parse buffer.
639 StatsdConfig config;
640 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700641 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700642 return UNKNOWN_ERROR;
643 }
644
645 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800646 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700647 } else {
yro74fed972017-11-27 14:42:42 -0800648 if (argCount == 2) {
649 cmd_remove_all_configs(out);
650 } else {
651 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800652 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800653 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700654 }
655
656 return NO_ERROR;
657 }
David Chen0656b7a2017-09-13 15:53:39 -0700658 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700659 print_cmd_help(out);
660 return UNKNOWN_ERROR;
661}
662
Bookatzff71cad2018-09-20 17:17:49 -0700663status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700664 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800665 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700666 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800667 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700668 bool includeCurrentBucket = false;
Bookatz3e906582018-12-10 17:26:58 -0800669 bool eraseData = true;
Yao Chen729093d2017-10-16 10:33:26 -0700670 int uid;
671 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800672 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
673 proto = true;
674 argCount -= 1;
675 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700676 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
677 includeCurrentBucket = true;
678 argCount -= 1;
679 }
Bookatz3e906582018-12-10 17:26:58 -0800680 if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
681 eraseData = false;
682 argCount -= 1;
683 }
Yao Chen729093d2017-10-16 10:33:26 -0700684 if (argCount == 2) {
685 // Automatically pick the UID
686 uid = IPCThreadState::self()->getCallingUid();
Yao Chen5154a3792017-10-30 22:57:06 -0700687 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700688 good = true;
689 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800690 good = getUidFromArgs(args, 1, uid);
691 if (!good) {
692 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
693 "other UIDs on eng or userdebug builds.\n");
Yao Chen729093d2017-10-16 10:33:26 -0700694 }
Bookatzd2386572018-12-14 15:53:14 -0800695 name.assign(args[2].c_str(), args[2].size());
Yao Chen729093d2017-10-16 10:33:26 -0700696 }
697 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800698 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800699 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000700 includeCurrentBucket, eraseData, ADB_DUMP,
701 NO_TIME_CONSTRAINTS,
702 &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800703 if (proto) {
704 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700705 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800706 }
707 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700708 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800709 }
Yao Chen729093d2017-10-16 10:33:26 -0700710 return android::OK;
711 } else {
712 // If arg parsing failed, print the help text and return an error.
713 print_cmd_help(out);
714 return UNKNOWN_ERROR;
715 }
716 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700717 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700718 return UNKNOWN_ERROR;
719 }
720}
721
Yao Chena80e5c02018-09-04 13:55:29 -0700722status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700723 int argCount = args.size();
724 bool proto = false;
725 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
726 proto = true;
727 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800728 }
Yao Chenb3561512017-11-21 18:07:17 -0800729 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700730 if (proto) {
731 vector<uint8_t> data;
732 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
733 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700734 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700735 }
736
737 } else {
738 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
739 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700740 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700741 mProcessor->GetMetricsSize(key));
742 }
743 statsdStats.dumpStats(out);
744 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800745 return NO_ERROR;
746}
747
Yao Chena80e5c02018-09-04 13:55:29 -0700748status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800749 if (args.size() > 1) {
750 string pkg;
751 pkg.assign(args[1].c_str(), args[1].size());
752 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700753 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800754 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700755 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800756 }
Yao Chena80e5c02018-09-04 13:55:29 -0700757 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800758 } else {
759 mUidMap->printUidMap(out);
760 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700761 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700762}
763
Yao Chena80e5c02018-09-04 13:55:29 -0700764status_t StatsService::cmd_write_data_to_disk(int out) {
765 dprintf(out, "Writing data to disk\n");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000766 mProcessor->WriteDataToDisk(ADB_DUMP, NO_TIME_CONSTRAINTS);
yro947fbce2017-11-15 22:50:23 -0800767 return NO_ERROR;
768}
769
Yao Chena80e5c02018-09-04 13:55:29 -0700770status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800771 bool good = false;
772 int32_t uid;
773 int32_t label;
774 int32_t state;
775 const int argCount = args.size();
776 if (argCount == 3) {
777 // Automatically pick the UID
778 uid = IPCThreadState::self()->getCallingUid();
779 label = atoi(args[1].c_str());
780 state = atoi(args[2].c_str());
781 good = true;
782 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800783 good = getUidFromArgs(args, 1, uid);
784 if (!good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700785 dprintf(out,
Bookatzd2386572018-12-14 15:53:14 -0800786 "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
787 "done for other UIDs on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800788 }
Bookatzd2386572018-12-14 15:53:14 -0800789 label = atoi(args[2].c_str());
790 state = atoi(args[3].c_str());
Bookatzb223c4e2018-02-01 15:35:04 -0800791 }
792 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700793 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
David Chen0b5c90c2018-01-25 16:51:49 -0800794 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800795 } else {
796 print_cmd_help(out);
797 return UNKNOWN_ERROR;
798 }
799 return NO_ERROR;
800}
801
Yao Chena80e5c02018-09-04 13:55:29 -0700802status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700803 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700804 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800805 if (mPullerManager->Pull(s, &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700806 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700807 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700808 }
Yao Chena80e5c02018-09-04 13:55:29 -0700809 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700810 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700811 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700812 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700813}
814
Yao Chena80e5c02018-09-04 13:55:29 -0700815status_t StatsService::cmd_remove_all_configs(int out) {
816 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800817 VLOG("StatsService::cmd_remove_all_configs was called");
818 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800819 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800820 return NO_ERROR;
821}
822
Yao Chena80e5c02018-09-04 13:55:29 -0700823status_t StatsService::cmd_dump_memory_info(int out) {
824 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800825 return NO_ERROR;
826}
827
Yao Chena80e5c02018-09-04 13:55:29 -0700828status_t StatsService::cmd_clear_puller_cache(int out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800829 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800830 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
831 ipc->getCallingPid(), ipc->getCallingUid());
Chenjie Yufa22d652018-02-05 14:37:48 -0800832 if (checkCallingPermission(String16(kPermissionDump))) {
Chenjie Yue2219202018-06-08 10:07:51 -0700833 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700834 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800835 return NO_ERROR;
836 } else {
837 return PERMISSION_DENIED;
838 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800839}
840
Yao Chena80e5c02018-09-04 13:55:29 -0700841status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Yao Chen876889c2018-05-02 11:16:16 -0700842 IPCThreadState* ipc = IPCThreadState::self();
843 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", ipc->getCallingPid(),
844 ipc->getCallingUid());
845 if (checkCallingPermission(String16(kPermissionDump))) {
846 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
876 int32_t callingUid = IPCThreadState::self()->getCallingUid();
877 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
Dianne Hackborn3accca02013-09-20 09:32:11 -0700882Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int64_t>& version,
dwchen730403e2018-10-29 11:41:56 -0700883 const vector<String16>& version_string,
884 const vector<String16>& app,
885 const vector<String16>& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600886 ENFORCE_UID(AID_SYSTEM);
887
yro74fed972017-11-27 14:42:42 -0800888 VLOG("StatsService::informAllUidData was called");
dwchen730403e2018-10-29 11:41:56 -0700889 mUidMap->updateMap(getElapsedRealtimeNs(), uid, version, version_string, app, installer);
yro74fed972017-11-27 14:42:42 -0800890 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700891
892 return Status::ok();
893}
894
dwchen730403e2018-10-29 11:41:56 -0700895Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version,
896 const String16& version_string, const String16& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600897 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700898
Jeff Sharkey6b649252018-04-16 09:50:22 -0600899 VLOG("StatsService::informOnePackage was called");
dwchen730403e2018-10-29 11:41:56 -0700900 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version, version_string, installer);
David Chende701692017-10-05 13:16:02 -0700901 return Status::ok();
902}
903
904Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600905 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700906
Jeff Sharkey6b649252018-04-16 09:50:22 -0600907 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -0700908 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -0800909 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -0700910 return Status::ok();
911}
912
Yao Chenef99c4f2017-09-22 16:26:54 -0700913Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600914 ENFORCE_UID(AID_SYSTEM);
915
yro74fed972017-11-27 14:42:42 -0800916 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700917 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800918 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
919 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
920 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -0800921 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -0800922 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -0800923 } else {
924 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
925 }
Bookatz1b0b1142017-09-08 11:58:42 -0700926 return Status::ok();
927}
928
Yangster-mac932ecec2018-02-01 10:23:52 -0800929Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600930 ENFORCE_UID(AID_SYSTEM);
931
Yangster-mac932ecec2018-02-01 10:23:52 -0800932 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700933 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800934 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
935 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
936 if (alarmSet.size() > 0) {
937 VLOG("Found periodic alarm fired.");
938 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
939 } else {
940 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
941 }
942 return Status::ok();
943}
944
Yao Chenef99c4f2017-09-22 16:26:54 -0700945Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600946 ENFORCE_UID(AID_SYSTEM);
947
yro74fed972017-11-27 14:42:42 -0800948 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700949 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -0800950 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700951 return Status::ok();
952}
953
Yao Chenef99c4f2017-09-22 16:26:54 -0700954Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600955 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700956
957 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800958 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -0700959 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700960 return Status::ok();
961}
962
Yangster-mac892f3d32018-05-02 14:16:48 -0700963Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600964 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -0700965 VLOG("StatsService::informDeviceShutdown");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000966 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN, FAST);
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800967 mProcessor->WriteMetricsActivationToDisk(getElapsedRealtimeNs());
yro947fbce2017-11-15 22:50:23 -0800968 return Status::ok();
969}
970
Yao Chenef99c4f2017-09-22 16:26:54 -0700971void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -0700972 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
973 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -0800974 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -0700975 statsCompanion->statsdReady();
976 } else {
yro74fed972017-11-27 14:42:42 -0800977 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -0700978 }
979}
980
Yao Chenef99c4f2017-09-22 16:26:54 -0700981Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600982 ENFORCE_UID(AID_SYSTEM);
983
yro74fed972017-11-27 14:42:42 -0800984 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -0700985 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
986 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700987 return Status::fromExceptionCode(
988 Status::EX_NULL_POINTER,
989 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700990 }
yro74fed972017-11-27 14:42:42 -0800991 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -0700992 IInterface::asBinder(statsCompanion)->linkToDeath(this);
Chenjie Yue2219202018-06-08 10:07:51 -0700993 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -0800994 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
995 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -0800996 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -0700997 return Status::ok();
998}
999
Joe Onorato9fc9edf2017-10-15 20:08:52 -07001000void StatsService::Startup() {
1001 mConfigManager->Startup();
Chenjie Yuc7939cb2019-02-04 17:25:45 -08001002 mProcessor->LoadMetricsActivationFromDisk();
Bookatz906a35c2017-09-20 15:26:44 -07001003}
1004
Yangster-mac97e7d202018-10-09 11:05:39 -07001005void StatsService::Terminate() {
1006 ALOGI("StatsService::Terminating");
1007 if (mProcessor != nullptr) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001008 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED, FAST);
Yangster-mac97e7d202018-10-09 11:05:39 -07001009 }
1010}
1011
Yao Chen3ff3a492018-08-06 16:17:37 -07001012void StatsService::OnLogEvent(LogEvent* event) {
1013 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -07001014 if (mShellSubscriber != nullptr) {
1015 mShellSubscriber->onLogEvent(*event);
1016 }
Bookatz906a35c2017-09-20 15:26:44 -07001017}
1018
Jeff Sharkey6b649252018-04-16 09:50:22 -06001019Status StatsService::getData(int64_t key, const String16& packageName, vector<uint8_t>* output) {
1020 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1021
David Chenadaf8b32017-11-03 15:42:08 -07001022 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -08001023 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001024 ConfigKey configKey(ipc->getCallingUid(), key);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001025 // The dump latency does not matter here since we do not include the current bucket, we do not
1026 // need to pull any new data anyhow.
David Chen56ae0d92018-05-11 16:00:22 -07001027 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001028 true /* erase_data */, GET_DATA_CALLED, FAST, output);
Bookatz4f716292018-04-10 17:15:12 -07001029 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001030}
1031
Jeff Sharkey6b649252018-04-16 09:50:22 -06001032Status StatsService::getMetadata(const String16& packageName, vector<uint8_t>* output) {
1033 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1034
David Chen2e8f3802017-11-22 10:56:48 -08001035 IPCThreadState* ipc = IPCThreadState::self();
1036 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
1037 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001038 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
1039 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -08001040}
1041
Jeff Sharkey6b649252018-04-16 09:50:22 -06001042Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
1043 const String16& packageName) {
1044 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1045
David Chenadaf8b32017-11-03 15:42:08 -07001046 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -07001047 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -08001048 return Status::ok();
1049 } else {
Bookatz4f716292018-04-10 17:15:12 -07001050 ALOGE("Could not parse malformatted StatsdConfig");
1051 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
1052 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -08001053 }
1054}
1055
David Chen9fdd4032018-03-20 14:38:56 -07001056bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
1057 ConfigKey configKey(uid, key);
1058 StatsdConfig cfg;
1059 if (config.size() > 0) { // If the config is empty, skip parsing.
1060 if (!cfg.ParseFromArray(&config[0], config.size())) {
1061 return false;
1062 }
1063 }
1064 mConfigManager->UpdateConfig(configKey, cfg);
1065 return true;
1066}
1067
Jeff Sharkey6b649252018-04-16 09:50:22 -06001068Status StatsService::removeDataFetchOperation(int64_t key, const String16& packageName) {
1069 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1070
Bookatz4f716292018-04-10 17:15:12 -07001071 IPCThreadState* ipc = IPCThreadState::self();
1072 ConfigKey configKey(ipc->getCallingUid(), key);
1073 mConfigManager->RemoveConfigReceiver(configKey);
1074 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -08001075}
1076
Jeff Sharkey6b649252018-04-16 09:50:22 -06001077Status StatsService::setDataFetchOperation(int64_t key,
1078 const sp<android::IBinder>& intentSender,
1079 const String16& packageName) {
1080 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1081
Bookatz4f716292018-04-10 17:15:12 -07001082 IPCThreadState* ipc = IPCThreadState::self();
1083 ConfigKey configKey(ipc->getCallingUid(), key);
1084 mConfigManager->SetConfigReceiver(configKey, intentSender);
David Chen48944902018-05-03 10:29:11 -07001085 if (StorageManager::hasConfigMetricsReport(configKey)) {
1086 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
1087 configKey.ToString().c_str());
1088 mProcessor->noteOnDiskData(configKey);
1089 }
Bookatz4f716292018-04-10 17:15:12 -07001090 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001091}
1092
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001093Status StatsService::setActiveConfigsChangedOperation(const sp<android::IBinder>& intentSender,
1094 const String16& packageName,
1095 vector<int64_t>* output) {
1096 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1097
1098 IPCThreadState* ipc = IPCThreadState::self();
Tej Singh6ede28b2019-01-29 17:06:54 -08001099 int uid = ipc->getCallingUid();
1100 mConfigManager->SetActiveConfigsChangedReceiver(uid, intentSender);
1101 if (output != nullptr) {
1102 mProcessor->GetActiveConfigs(uid, *output);
1103 } else {
1104 ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
1105 }
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001106 return Status::ok();
1107}
1108
1109Status StatsService::removeActiveConfigsChangedOperation(const String16& packageName) {
1110 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1111
1112 IPCThreadState* ipc = IPCThreadState::self();
1113 mConfigManager->RemoveActiveConfigsChangedReceiver(ipc->getCallingUid());
1114 return Status::ok();
1115}
1116
Jeff Sharkey6b649252018-04-16 09:50:22 -06001117Status StatsService::removeConfiguration(int64_t key, const String16& packageName) {
1118 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1119
Bookatz4f716292018-04-10 17:15:12 -07001120 IPCThreadState* ipc = IPCThreadState::self();
1121 ConfigKey configKey(ipc->getCallingUid(), key);
1122 mConfigManager->RemoveConfig(configKey);
1123 SubscriberReporter::getInstance().removeConfig(configKey);
1124 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001125}
1126
Bookatzc6977972018-01-16 16:55:05 -08001127Status StatsService::setBroadcastSubscriber(int64_t configId,
1128 int64_t subscriberId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001129 const sp<android::IBinder>& intentSender,
1130 const String16& packageName) {
1131 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1132
Bookatzc6977972018-01-16 16:55:05 -08001133 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001134 IPCThreadState* ipc = IPCThreadState::self();
1135 ConfigKey configKey(ipc->getCallingUid(), configId);
1136 SubscriberReporter::getInstance()
1137 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
1138 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001139}
1140
1141Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001142 int64_t subscriberId,
1143 const String16& packageName) {
1144 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1145
Bookatzc6977972018-01-16 16:55:05 -08001146 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001147 IPCThreadState* ipc = IPCThreadState::self();
1148 ConfigKey configKey(ipc->getCallingUid(), configId);
1149 SubscriberReporter::getInstance()
1150 .unsetBroadcastSubscriber(configKey, subscriberId);
1151 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001152}
1153
yrobe6d7f92018-05-04 13:02:53 -07001154Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
1155 // Permission check not necessary as it's meant for applications to write to
1156 // statsd.
1157 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
1158 IPCThreadState::self()->getCallingUid(), label,
1159 state);
1160 return Status::ok();
1161}
1162
Tej Singha0c89dd2019-01-25 16:39:18 -08001163Status StatsService::registerPullerCallback(int32_t atomTag,
1164 const sp<android::os::IStatsPullerCallback>& pullerCallback,
1165 const String16& packageName) {
1166 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1167
1168 VLOG("StatsService::registerPullerCallback called.");
1169 mPullerManager->RegisterPullerCallback(atomTag, pullerCallback);
1170 return Status::ok();
1171}
1172
1173Status StatsService::unregisterPullerCallback(int32_t atomTag, const String16& packageName) {
1174 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1175
1176 VLOG("StatsService::unregisterPullerCallback called.");
1177 mPullerManager->UnregisterPullerCallback(atomTag);
1178 return Status::ok();
1179}
1180
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001181Status StatsService::sendBinaryPushStateChangedAtom(const android::String16& trainName,
1182 int64_t trainVersionCode, int options,
1183 int32_t state,
1184 const std::vector<int64_t>& experimentIds) {
1185 uid_t uid = IPCThreadState::self()->getCallingUid();
1186 // For testing
1187 if (uid == AID_ROOT || uid == AID_SYSTEM || uid == AID_SHELL) {
1188 return ok();
1189 }
1190
1191 // Caller must be granted these permissions
1192 if (!checkCallingPermission(String16(kPermissionDump))) {
1193 return exception(binder::Status::EX_SECURITY,
1194 StringPrintf("UID %d lacks permission %s", uid, kPermissionDump));
1195 }
1196 if (!checkCallingPermission(String16(kPermissionUsage))) {
1197 return exception(binder::Status::EX_SECURITY,
1198 StringPrintf("UID %d lacks permission %s", uid, kPermissionUsage));
1199 }
1200 // TODO: add verifier permission
1201
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001202 bool readTrainInfoSuccess = false;
1203 InstallTrainInfo trainInfo;
1204 if (trainVersionCode == -1 || experimentIds.empty() || trainName.size() == 0) {
1205 readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfo);
1206 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001207
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001208 if (trainVersionCode == -1 && readTrainInfoSuccess) {
1209 trainVersionCode = trainInfo.trainVersionCode;
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001210 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001211
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001212 vector<uint8_t> experimentIdsProtoBuffer;
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001213 if (readTrainInfoSuccess && experimentIds.empty()) {
1214 experimentIdsProtoBuffer = trainInfo.experimentIds;
1215 } else {
1216 ProtoOutputStream proto;
1217 for (const auto& expId : experimentIds) {
1218 proto.write(FIELD_TYPE_INT64 | FIELD_COUNT_REPEATED | FIELD_ID_EXPERIMENT_ID,
1219 (long long)expId);
1220 }
1221
1222 experimentIdsProtoBuffer.resize(proto.size());
1223 size_t pos = 0;
Joe Onorato99598ee2019-02-11 15:55:13 +00001224 sp<ProtoReader> reader = proto.data();
1225 while (reader->readBuffer() != NULL) {
1226 size_t toRead = reader->currentToRead();
1227 std::memcpy(&(experimentIdsProtoBuffer[pos]), reader->readBuffer(), toRead);
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001228 pos += toRead;
Joe Onorato99598ee2019-02-11 15:55:13 +00001229 reader->move(toRead);
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001230 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001231 }
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001232
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001233 std::string trainNameUtf8;
1234 if (readTrainInfoSuccess && trainName.size() == 0) {
1235 trainNameUtf8 = trainInfo.trainName;
1236 } else {
1237 trainNameUtf8 = std::string(String8(trainName).string());
1238 }
1239
1240 userid_t userId = multiuser_get_user_id(uid);
1241 bool requiresStaging = options & IStatsManager::FLAG_REQUIRE_STAGING;
1242 bool rollbackEnabled = options & IStatsManager::FLAG_ROLLBACK_ENABLED;
1243 bool requiresLowLatencyMonitor = options & IStatsManager::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001244 LogEvent event(trainNameUtf8, trainVersionCode, requiresStaging, rollbackEnabled,
1245 requiresLowLatencyMonitor, state, experimentIdsProtoBuffer, userId);
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001246 mProcessor->OnLogEvent(&event);
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001247 StorageManager::writeTrainInfo(trainVersionCode, trainNameUtf8, state, experimentIdsProtoBuffer);
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001248 return Status::ok();
1249}
1250
Howard Roa46b6582018-09-18 16:45:02 -07001251hardware::Return<void> StatsService::reportSpeakerImpedance(
1252 const SpeakerImpedance& speakerImpedance) {
Tej Singh8928ed72019-02-22 19:06:22 -08001253 android::util::stats_write(android::util::SPEAKER_IMPEDANCE_REPORTED,
1254 speakerImpedance.speakerLocation, speakerImpedance.milliOhms);
Howard Roa46b6582018-09-18 16:45:02 -07001255
1256 return hardware::Void();
1257}
1258
1259hardware::Return<void> StatsService::reportHardwareFailed(const HardwareFailed& hardwareFailed) {
Tej Singh8928ed72019-02-22 19:06:22 -08001260 android::util::stats_write(android::util::HARDWARE_FAILED, int32_t(hardwareFailed.hardwareType),
1261 hardwareFailed.hardwareLocation, int32_t(hardwareFailed.errorCode));
Howard Roa46b6582018-09-18 16:45:02 -07001262
1263 return hardware::Void();
1264}
1265
1266hardware::Return<void> StatsService::reportPhysicalDropDetected(
1267 const PhysicalDropDetected& physicalDropDetected) {
Tej Singh8928ed72019-02-22 19:06:22 -08001268 android::util::stats_write(android::util::PHYSICAL_DROP_DETECTED,
1269 int32_t(physicalDropDetected.confidencePctg), physicalDropDetected.accelPeak,
1270 physicalDropDetected.freefallDuration);
Howard Roa46b6582018-09-18 16:45:02 -07001271
1272 return hardware::Void();
1273}
1274
1275hardware::Return<void> StatsService::reportChargeCycles(const ChargeCycles& chargeCycles) {
Tej Singh8928ed72019-02-22 19:06:22 -08001276 std::vector<int32_t> buckets = chargeCycles.cycleBucket;
1277 int initialSize = buckets.size();
1278 for (int i = 0; i < 10 - initialSize; i++) {
1279 buckets.push_back(-1); // Push -1 for buckets that do not exist.
1280 }
1281 android::util::stats_write(android::util::CHARGE_CYCLES_REPORTED, buckets[0], buckets[1],
1282 buckets[2], buckets[3], buckets[4], buckets[5], buckets[6], buckets[7], buckets[8],
1283 buckets[9]);
Howard Roa46b6582018-09-18 16:45:02 -07001284
1285 return hardware::Void();
1286}
1287
1288hardware::Return<void> StatsService::reportBatteryHealthSnapshot(
1289 const BatteryHealthSnapshotArgs& batteryHealthSnapshotArgs) {
Tej Singh8928ed72019-02-22 19:06:22 -08001290 android::util::stats_write(android::util::BATTERY_HEALTH_SNAPSHOT,
1291 int32_t(batteryHealthSnapshotArgs.type), batteryHealthSnapshotArgs.temperatureDeciC,
1292 batteryHealthSnapshotArgs.voltageMicroV, batteryHealthSnapshotArgs.currentMicroA,
1293 batteryHealthSnapshotArgs.openCircuitVoltageMicroV,
1294 batteryHealthSnapshotArgs.resistanceMicroOhm, batteryHealthSnapshotArgs.levelPercent);
Howard Roa46b6582018-09-18 16:45:02 -07001295
1296 return hardware::Void();
1297}
1298
1299hardware::Return<void> StatsService::reportSlowIo(const SlowIo& slowIo) {
Tej Singh8928ed72019-02-22 19:06:22 -08001300 android::util::stats_write(android::util::SLOW_IO, int32_t(slowIo.operation), slowIo.count);
Howard Roa46b6582018-09-18 16:45:02 -07001301
1302 return hardware::Void();
1303}
1304
1305hardware::Return<void> StatsService::reportBatteryCausedShutdown(
1306 const BatteryCausedShutdown& batteryCausedShutdown) {
Tej Singh8928ed72019-02-22 19:06:22 -08001307 android::util::stats_write(android::util::BATTERY_CAUSED_SHUTDOWN,
1308 batteryCausedShutdown.voltageMicroV);
Howard Roa46b6582018-09-18 16:45:02 -07001309
1310 return hardware::Void();
1311}
1312
Maggie Whitefc1aa592018-11-28 21:55:23 -08001313hardware::Return<void> StatsService::reportUsbPortOverheatEvent(
1314 const UsbPortOverheatEvent& usbPortOverheatEvent) {
Tej Singh8928ed72019-02-22 19:06:22 -08001315 android::util::stats_write(android::util::USB_PORT_OVERHEAT_EVENT_REPORTED,
1316 usbPortOverheatEvent.plugTemperatureDeciC, usbPortOverheatEvent.maxTemperatureDeciC,
1317 usbPortOverheatEvent.timeToOverheat, usbPortOverheatEvent.timeToHysteresis,
1318 usbPortOverheatEvent.timeToInactive);
Maggie Whitefc1aa592018-11-28 21:55:23 -08001319
1320 return hardware::Void();
1321}
1322
Carter Hsub8fd1e92019-01-11 15:24:45 +08001323hardware::Return<void> StatsService::reportSpeechDspStat(
1324 const SpeechDspStat& speechDspStat) {
Tej Singh8928ed72019-02-22 19:06:22 -08001325 android::util::stats_write(android::util::SPEECH_DSP_STAT_REPORTED,
1326 speechDspStat.totalUptimeMillis, speechDspStat.totalDowntimeMillis,
1327 speechDspStat.totalCrashCount, speechDspStat.totalRecoverCount);
Carter Hsub8fd1e92019-01-11 15:24:45 +08001328
1329 return hardware::Void();
1330}
1331
Maggie White58174da2019-01-18 15:23:35 -08001332hardware::Return<void> StatsService::reportVendorAtom(const VendorAtom& vendorAtom) {
1333 std::string reverseDomainName = (std::string) vendorAtom.reverseDomainName;
1334 if (vendorAtom.atomId < 100000 || vendorAtom.atomId >= 200000) {
1335 ALOGE("Atom ID %ld is not a valid vendor atom ID", (long) vendorAtom.atomId);
1336 return hardware::Void();
1337 }
1338 if (reverseDomainName.length() > 50) {
1339 ALOGE("Vendor atom reverse domain name %s is too long.", reverseDomainName.c_str());
1340 return hardware::Void();
1341 }
1342 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), vendorAtom);
1343 mProcessor->OnLogEvent(&event);
1344
1345 return hardware::Void();
1346}
1347
David Chen1d7b0cd2017-11-15 14:20:04 -08001348void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001349 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001350 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1351 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001352 ALOGW("Reset statsd upon system server restarts.");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001353 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED, FAST);
Yangster-mac892f3d32018-05-02 14:16:48 -07001354 mProcessor->resetConfigs();
1355 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001356 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1357 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
1358 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001359 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001360}
1361
Yao Chenef99c4f2017-09-22 16:26:54 -07001362} // namespace statsd
1363} // namespace os
1364} // namespace android