blob: 69fbf1f9d881651fbe9010b5bf9d16aafdbb8dc6 [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;
Jeff Sharkey6b649252018-04-16 09:50:22 -060053
Bookatz906a35c2017-09-20 15:26:44 -070054namespace android {
55namespace os {
56namespace statsd {
57
David Chenadaf8b32017-11-03 15:42:08 -070058constexpr const char* kPermissionDump = "android.permission.DUMP";
Jeff Sharkey6b649252018-04-16 09:50:22 -060059constexpr const char* kPermissionUsage = "android.permission.PACKAGE_USAGE_STATS";
60
61constexpr const char* kOpUsage = "android:get_usage_stats";
62
yro03faf092017-12-12 00:17:50 -080063#define STATS_SERVICE_DIR "/data/misc/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070064
Bookatzff71cad2018-09-20 17:17:49 -070065// for StatsDataDumpProto
66const int FIELD_ID_REPORTS_LIST = 1;
Chenjie Yu97dbb202019-02-13 16:42:04 -080067// for TrainInfo experiment id serialization
68const int FIELD_ID_EXPERIMENT_ID = 1;
Bookatzff71cad2018-09-20 17:17:49 -070069
Jeff Sharkey6b649252018-04-16 09:50:22 -060070static binder::Status ok() {
71 return binder::Status::ok();
72}
73
74static binder::Status exception(uint32_t code, const std::string& msg) {
75 ALOGE("%s (%d)", msg.c_str(), code);
76 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
77}
78
79binder::Status checkUid(uid_t expectedUid) {
80 uid_t uid = IPCThreadState::self()->getCallingUid();
81 if (uid == expectedUid || uid == AID_ROOT) {
82 return ok();
83 } else {
84 return exception(binder::Status::EX_SECURITY,
85 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
86 }
87}
88
89binder::Status checkDumpAndUsageStats(const String16& packageName) {
90 pid_t pid = IPCThreadState::self()->getCallingPid();
91 uid_t uid = IPCThreadState::self()->getCallingUid();
92
93 // Root, system, and shell always have access
94 if (uid == AID_ROOT || uid == AID_SYSTEM || uid == AID_SHELL) {
95 return ok();
96 }
97
98 // Caller must be granted these permissions
99 if (!checkCallingPermission(String16(kPermissionDump))) {
100 return exception(binder::Status::EX_SECURITY,
101 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionDump));
102 }
103 if (!checkCallingPermission(String16(kPermissionUsage))) {
104 return exception(binder::Status::EX_SECURITY,
105 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionUsage));
106 }
107
108 // Caller must also have usage stats op granted
109 PermissionController pc;
110 switch (pc.noteOp(String16(kOpUsage), uid, packageName)) {
111 case PermissionController::MODE_ALLOWED:
112 case PermissionController::MODE_DEFAULT:
113 return ok();
114 default:
115 return exception(binder::Status::EX_SECURITY,
116 StringPrintf("UID %d / PID %d lacks app-op %s", uid, pid, kOpUsage));
117 }
118}
119
120#define ENFORCE_UID(uid) { \
121 binder::Status status = checkUid((uid)); \
122 if (!status.isOk()) { \
123 return status; \
124 } \
125}
126
127#define ENFORCE_DUMP_AND_USAGE_STATS(packageName) { \
128 binder::Status status = checkDumpAndUsageStats(packageName); \
129 if (!status.isOk()) { \
130 return status; \
131 } \
132}
133
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700134StatsService::StatsService(const sp<Looper>& handlerLooper)
Yangster-mac932ecec2018-02-01 10:23:52 -0800135 : mAnomalyAlarmMonitor(new AlarmMonitor(MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
136 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
137 if (sc != nullptr) {
138 sc->setAnomalyAlarm(timeMillis);
139 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
140 }
141 },
142 [](const sp<IStatsCompanionService>& sc) {
143 if (sc != nullptr) {
144 sc->cancelAnomalyAlarm();
145 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
146 }
147 })),
148 mPeriodicAlarmMonitor(new AlarmMonitor(MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
149 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
150 if (sc != nullptr) {
151 sc->setAlarmForSubscriberTriggering(timeMillis);
152 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
153 }
154 },
155 [](const sp<IStatsCompanionService>& sc) {
156 if (sc != nullptr) {
157 sc->cancelAlarmForSubscriberTriggering();
158 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
159 }
160
161 })) {
Yao Chen4ce07292019-02-13 13:06:36 -0800162 mUidMap = UidMap::getInstance();
Chenjie Yue2219202018-06-08 10:07:51 -0700163 mPullerManager = new StatsPullerManager();
Chenjie Yu80f91122018-01-31 20:24:50 -0800164 StatsPuller::SetUidMap(mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700165 mConfigManager = new ConfigManager();
Chenjie Yue2219202018-06-08 10:07:51 -0700166 mProcessor = new StatsLogProcessor(
167 mUidMap, mPullerManager, mAnomalyAlarmMonitor, mPeriodicAlarmMonitor,
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800168 getElapsedRealtimeNs(),
169 [this](const ConfigKey& key) {
Chenjie Yue2219202018-06-08 10:07:51 -0700170 sp<IStatsCompanionService> sc = getStatsCompanionService();
171 auto receiver = mConfigManager->GetConfigReceiver(key);
172 if (sc == nullptr) {
173 VLOG("Could not find StatsCompanionService");
174 return false;
175 } else if (receiver == nullptr) {
176 VLOG("Statscompanion could not find a broadcast receiver for %s",
177 key.ToString().c_str());
178 return false;
179 } else {
180 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
181 return true;
182 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800183 },
184 [this](const int& uid, const vector<int64_t>& activeConfigs) {
185 auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
186 sp<IStatsCompanionService> sc = getStatsCompanionService();
187 if (sc == nullptr) {
188 VLOG("Could not access statsCompanion");
189 return false;
190 } else if (receiver == nullptr) {
191 VLOG("Could not find receiver for uid %d", uid);
192 return false;
193 } else {
194 sc->sendActiveConfigsChangedBroadcast(receiver, activeConfigs);
195 VLOG("StatsService::active configs broadcast succeeded for uid %d" , uid);
196 return true;
197 }
Chenjie Yue2219202018-06-08 10:07:51 -0700198 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700199
200 mConfigManager->AddListener(mProcessor);
201
202 init_system_properties();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700203}
204
Yao Chenef99c4f2017-09-22 16:26:54 -0700205StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700206}
207
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700208void StatsService::init_system_properties() {
209 mEngBuild = false;
210 const prop_info* buildType = __system_property_find("ro.build.type");
211 if (buildType != NULL) {
212 __system_property_read_callback(buildType, init_build_type_callback, this);
213 }
David Chen0656b7a2017-09-13 15:53:39 -0700214}
215
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700216void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
217 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700218 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700219 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
220 }
221}
222
223/**
224 * Implement our own because the default binder implementation isn't
225 * properly handling SHELL_COMMAND_TRANSACTION.
226 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700227status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
228 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700229 switch (code) {
230 case SHELL_COMMAND_TRANSACTION: {
231 int in = data.readFileDescriptor();
232 int out = data.readFileDescriptor();
233 int err = data.readFileDescriptor();
234 int argc = data.readInt32();
235 Vector<String8> args;
236 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
237 args.add(String8(data.readString16()));
238 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700239 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
240 sp<IResultReceiver> resultReceiver =
241 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700242
Yao Chena80e5c02018-09-04 13:55:29 -0700243 err = command(in, out, err, args, resultReceiver);
244 resultReceiver->send(err);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700245 return NO_ERROR;
246 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700247 default: { return BnStatsManager::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700248 }
249}
250
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700251/**
Bookatzff71cad2018-09-20 17:17:49 -0700252 * Write data from statsd.
253 * Format for statsdStats: adb shell dumpsys stats --metadata [-v] [--proto]
254 * Format for data report: adb shell dumpsys stats [anything other than --metadata] [--proto]
255 * Anything ending in --proto will be in proto format.
256 * Anything without --metadata as the first argument will be report information.
257 * (bugreports call "adb shell dumpsys stats --dump-priority NORMAL -a --proto")
258 * TODO: Come up with a more robust method of enacting <serviceutils/PriorityDumper.h>.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700259 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700260status_t StatsService::dump(int fd, const Vector<String16>& args) {
Tej Singhdd83d702018-04-10 17:24:50 -0700261 if (!checkCallingPermission(String16(kPermissionDump))) {
262 return PERMISSION_DENIED;
263 }
Bookatzff71cad2018-09-20 17:17:49 -0700264 int lastArg = args.size() - 1;
265 bool asProto = false;
266 if (lastArg >= 0 && !args[lastArg].compare(String16("--proto"))) { // last argument
267 asProto = true;
268 lastArg--;
Yao Chen884c8c12018-01-26 10:36:25 -0800269 }
Bookatzff71cad2018-09-20 17:17:49 -0700270 if (args.size() > 0 && !args[0].compare(String16("--metadata"))) { // first argument
271 // Request is to dump statsd stats.
272 bool verbose = false;
273 if (lastArg >= 0 && !args[lastArg].compare(String16("-v"))) {
274 verbose = true;
275 lastArg--;
276 }
277 dumpStatsdStats(fd, verbose, asProto);
278 } else {
279 // Request is to dump statsd report data.
280 if (asProto) {
281 dumpIncidentSection(fd);
282 } else {
283 dprintf(fd, "Non-proto format of stats data dump not available; see proto version.\n");
284 }
Tej Singh41b3f9a2018-04-03 17:06:35 -0700285 }
Yao Chen884c8c12018-01-26 10:36:25 -0800286
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700287 return NO_ERROR;
288}
289
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700290/**
Tej Singh41b3f9a2018-04-03 17:06:35 -0700291 * Write debugging data about statsd in text or proto format.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700292 */
Bookatzff71cad2018-09-20 17:17:49 -0700293void StatsService::dumpStatsdStats(int out, bool verbose, bool proto) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700294 if (proto) {
295 vector<uint8_t> data;
296 StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
297 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700298 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700299 }
300 } else {
301 StatsdStats::getInstance().dumpStats(out);
302 mProcessor->dumpStates(out, verbose);
303 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700304}
305
306/**
Bookatzff71cad2018-09-20 17:17:49 -0700307 * Write stats report data in StatsDataDumpProto incident section format.
308 */
309void StatsService::dumpIncidentSection(int out) {
310 ProtoOutputStream proto;
311 for (const ConfigKey& configKey : mConfigManager->GetAllConfigKeys()) {
312 uint64_t reportsListToken =
313 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS_LIST);
314 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
315 true /* includeCurrentBucket */, false /* erase_data */,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000316 ADB_DUMP,
317 FAST,
318 &proto);
Bookatzff71cad2018-09-20 17:17:49 -0700319 proto.end(reportsListToken);
320 proto.flush(out);
Bookatzc71d9012018-12-19 12:28:38 -0800321 proto.clear();
Bookatzff71cad2018-09-20 17:17:49 -0700322 }
323}
324
325/**
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700326 * Implementation of the adb shell cmd stats command.
327 */
Yao Chena80e5c02018-09-04 13:55:29 -0700328status_t StatsService::command(int in, int out, int err, Vector<String8>& args,
329 sp<IResultReceiver> resultReceiver) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600330 uid_t uid = IPCThreadState::self()->getCallingUid();
331 if (uid != AID_ROOT && uid != AID_SHELL) {
332 return PERMISSION_DENIED;
333 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700334
335 const int argCount = args.size();
336 if (argCount >= 1) {
337 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700338 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700339 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700340 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700341
David Chende701692017-10-05 13:16:02 -0700342 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800343 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700344 }
Yao Chen729093d2017-10-16 10:33:26 -0700345
346 if (!args[0].compare(String8("dump-report"))) {
Bookatzff71cad2018-09-20 17:17:49 -0700347 return cmd_dump_report(out, args);
Yao Chen729093d2017-10-16 10:33:26 -0700348 }
David Chen1481fe12017-10-16 13:16:34 -0700349
350 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
351 return cmd_print_pulled_metrics(out, args);
352 }
David Chenadaf8b32017-11-03 15:42:08 -0700353
354 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800355 return cmd_trigger_broadcast(out, args);
356 }
357
358 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800359 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700360 }
yro87d983c2017-11-14 21:31:43 -0800361
Yao Chen8d9989b2017-11-18 18:54:50 -0800362 if (!args[0].compare(String8("meminfo"))) {
363 return cmd_dump_memory_info(out);
364 }
yro947fbce2017-11-15 22:50:23 -0800365
366 if (!args[0].compare(String8("write-to-disk"))) {
367 return cmd_write_data_to_disk(out);
368 }
Bookatzb223c4e2018-02-01 15:35:04 -0800369
David Chen0b5c90c2018-01-25 16:51:49 -0800370 if (!args[0].compare(String8("log-app-breadcrumb"))) {
371 return cmd_log_app_breadcrumb(out, args);
Bookatzb223c4e2018-02-01 15:35:04 -0800372 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800373
374 if (!args[0].compare(String8("clear-puller-cache"))) {
375 return cmd_clear_puller_cache(out);
376 }
Yao Chen876889c2018-05-02 11:16:16 -0700377
378 if (!args[0].compare(String8("print-logs"))) {
379 return cmd_print_logs(out, args);
380 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800381 if (!args[0].compare(String8("send-active-configs"))) {
382 return cmd_trigger_active_config_broadcast(out, args);
383 }
Yao Chena80e5c02018-09-04 13:55:29 -0700384 if (!args[0].compare(String8("data-subscribe"))) {
385 if (mShellSubscriber == nullptr) {
Yao Chen41e606c2018-10-05 15:54:11 -0700386 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
Yao Chena80e5c02018-09-04 13:55:29 -0700387 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800388 int timeoutSec = -1;
389 if (argCount >= 2) {
390 timeoutSec = atoi(args[1].c_str());
391 }
392 mShellSubscriber->startNewSubscription(in, out, resultReceiver, timeoutSec);
Yao Chena80e5c02018-09-04 13:55:29 -0700393 return NO_ERROR;
394 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700395 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700396
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700397 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700398 return NO_ERROR;
399}
400
Yao Chena80e5c02018-09-04 13:55:29 -0700401void StatsService::print_cmd_help(int out) {
402 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700403 "usage: adb shell cmd stats print-stats-log [tag_required] "
404 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700405 dprintf(out, "\n");
406 dprintf(out, "\n");
407 dprintf(out, "usage: adb shell cmd stats meminfo\n");
408 dprintf(out, "\n");
409 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
410 dprintf(out, " # adb shell stop\n");
411 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
412 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
413 dprintf(out, " # adb shell start\n");
414 dprintf(out, "\n");
415 dprintf(out, "\n");
416 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
417 dprintf(out, "\n");
418 dprintf(out, " Prints the UID, app name, version mapping.\n");
419 dprintf(out, " PKG Optional package name to print the uids of the package\n");
420 dprintf(out, "\n");
421 dprintf(out, "\n");
422 dprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
423 dprintf(out, "\n");
424 dprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
425 dprintf(out, "\n");
426 dprintf(out, "\n");
427 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
428 dprintf(out, "\n");
429 dprintf(out, " Flushes all data on memory to disk.\n");
430 dprintf(out, "\n");
431 dprintf(out, "\n");
432 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
433 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
434 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
435 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
436 dprintf(out, " uid is used.\n");
437 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
438 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
439 dprintf(out, "\n");
440 dprintf(out, "\n");
441 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
442 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
443 dprintf(out, "\n");
444 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
445 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
446 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
447 dprintf(out, "\n");
448 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
449 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
450 dprintf(out, " uid is used.\n");
451 dprintf(out, " NAME The per-uid name to use\n");
452 dprintf(out, "\n");
453 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
454 dprintf(out, "\n be removed from memory and disk!\n");
455 dprintf(out, "\n");
456 dprintf(out,
Bookatz3e906582018-12-10 17:26:58 -0800457 "usage: adb shell cmd stats dump-report [UID] NAME [--keep_data] "
458 "[--include_current_bucket] [--proto]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700459 dprintf(out, " Dump all metric data for a configuration.\n");
460 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
461 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
462 dprintf(out, " calling uid is used.\n");
463 dprintf(out, " NAME The name of the configuration\n");
Bookatz3e906582018-12-10 17:26:58 -0800464 dprintf(out, " --keep_data Do NOT erase the data upon dumping it.\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700465 dprintf(out, " --proto Print proto binary.\n");
466 dprintf(out, "\n");
467 dprintf(out, "\n");
468 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
469 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
470 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
471 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
472 dprintf(out, " calling uid is used.\n");
473 dprintf(out, " NAME The name of the configuration\n");
474 dprintf(out, "\n");
475 dprintf(out, "\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800476 dprintf(out,
477 "usage: adb shell cmd stats send-active-configs [--uid=UID] [--configs] "
478 "[NAME1] [NAME2] [NAME3..]\n");
479 dprintf(out, " Send a broadcast that informs the subscriber of the current active configs.\n");
480 dprintf(out, " --uid=UID The uid of the configurations. It is only possible to pass\n");
481 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
482 dprintf(out, " calling uid is used.\n");
483 dprintf(out, " --configs Send the list of configs in the name list instead of\n");
484 dprintf(out, " the currently active configs\n");
485 dprintf(out, " NAME LIST List of configuration names to be included in the broadcast.\n");
486
487 dprintf(out, "\n");
488 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700489 dprintf(out, "usage: adb shell cmd stats print-stats\n");
490 dprintf(out, " Prints some basic stats.\n");
491 dprintf(out, " --proto Print proto binary instead of string format.\n");
492 dprintf(out, "\n");
493 dprintf(out, "\n");
494 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
495 dprintf(out, " Clear cached puller data.\n");
496 dprintf(out, "\n");
497 dprintf(out, "usage: adb shell cmd stats print-logs\n");
498 dprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700499}
500
Yao Chena80e5c02018-09-04 13:55:29 -0700501status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800502 string name;
503 bool good = false;
504 int uid;
505 const int argCount = args.size();
506 if (argCount == 2) {
507 // Automatically pick the UID
508 uid = IPCThreadState::self()->getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800509 name.assign(args[1].c_str(), args[1].size());
510 good = true;
511 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800512 good = getUidFromArgs(args, 1, uid);
513 if (!good) {
514 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
515 "other UIDs on eng or userdebug builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800516 }
Bookatzd2386572018-12-14 15:53:14 -0800517 name.assign(args[2].c_str(), args[2].size());
David Chen1d7b0cd2017-11-15 14:20:04 -0800518 }
519 if (!good) {
520 print_cmd_help(out);
521 return UNKNOWN_ERROR;
522 }
David Chend37bc232018-04-12 18:05:11 -0700523 ConfigKey key(uid, StrToInt64(name));
524 auto receiver = mConfigManager->GetConfigReceiver(key);
yro4d889e62017-11-17 15:44:48 -0800525 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen661f7912018-01-22 17:46:24 -0800526 if (sc == nullptr) {
527 VLOG("Could not access statsCompanion");
528 } else if (receiver == nullptr) {
529 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str())
530 } else {
David Chend37bc232018-04-12 18:05:11 -0700531 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
yro74fed972017-11-27 14:42:42 -0800532 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
533 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800534 }
535
David Chenadaf8b32017-11-03 15:42:08 -0700536 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700537}
538
Tej Singh6ede28b2019-01-29 17:06:54 -0800539status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
540 const int argCount = args.size();
541 int uid;
542 vector<int64_t> configIds;
543 if (argCount == 1) {
544 // Automatically pick the uid and send a broadcast that has no active configs.
545 uid = IPCThreadState::self()->getCallingUid();
546 mProcessor->GetActiveConfigs(uid, configIds);
547 } else {
548 int curArg = 1;
549 if(args[curArg].find("--uid=") == 0) {
550 string uidArgStr(args[curArg].c_str());
551 string uidStr = uidArgStr.substr(6);
552 if (!getUidFromString(uidStr.c_str(), uid)) {
553 dprintf(out, "Invalid UID. Note that the config can only be set for "
554 "other UIDs on eng or userdebug builds.\n");
555 return UNKNOWN_ERROR;
556 }
557 curArg++;
558 } else {
559 uid = IPCThreadState::self()->getCallingUid();
560 }
561 if (curArg == argCount || args[curArg] != "--configs") {
562 VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
563 mProcessor->GetActiveConfigs(uid, configIds);
564 } else {
565 // Flag specified, use the given list of configs.
566 curArg++;
567 for (int i = curArg; i < argCount; i++) {
568 char* endp;
569 int64_t configID = strtoll(args[i].c_str(), &endp, 10);
570 if (endp == args[i].c_str() || *endp != '\0') {
571 dprintf(out, "Error parsing config ID.\n");
572 return UNKNOWN_ERROR;
573 }
574 VLOG("Adding config id %ld", static_cast<long>(configID));
575 configIds.push_back(configID);
576 }
577 }
578 }
579 auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
580 sp<IStatsCompanionService> sc = getStatsCompanionService();
581 if (sc == nullptr) {
582 VLOG("Could not access statsCompanion");
583 } else if (receiver == nullptr) {
584 VLOG("Could not find receiver for uid %d", uid);
585 } else {
586 sc->sendActiveConfigsChangedBroadcast(receiver, configIds);
587 VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
588 }
589 return NO_ERROR;
590}
591
Yao Chena80e5c02018-09-04 13:55:29 -0700592status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700593 const int argCount = args.size();
594 if (argCount >= 2) {
595 if (args[1] == "update" || args[1] == "remove") {
596 bool good = false;
597 int uid = -1;
598 string name;
599
600 if (argCount == 3) {
601 // Automatically pick the UID
602 uid = IPCThreadState::self()->getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700603 name.assign(args[2].c_str(), args[2].size());
604 good = true;
605 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800606 good = getUidFromArgs(args, 2, uid);
607 if (!good) {
608 dprintf(err, "Invalid UID. Note that the config can only be set for "
609 "other UIDs on eng or userdebug builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700610 }
Bookatzd2386572018-12-14 15:53:14 -0800611 name.assign(args[3].c_str(), args[3].size());
yroe5f82922018-01-22 18:37:27 -0800612 } else if (argCount == 2 && args[1] == "remove") {
613 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700614 }
615
616 if (!good) {
617 // If arg parsing failed, print the help text and return an error.
618 print_cmd_help(out);
619 return UNKNOWN_ERROR;
620 }
621
622 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800623 char* endp;
624 int64_t configID = strtoll(name.c_str(), &endp, 10);
625 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700626 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800627 return UNKNOWN_ERROR;
628 }
629
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700630 // Read stream into buffer.
631 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700632 if (!android::base::ReadFdToString(in, &buffer)) {
633 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700634 return UNKNOWN_ERROR;
635 }
636
637 // Parse buffer.
638 StatsdConfig config;
639 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700640 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700641 return UNKNOWN_ERROR;
642 }
643
644 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800645 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700646 } else {
yro74fed972017-11-27 14:42:42 -0800647 if (argCount == 2) {
648 cmd_remove_all_configs(out);
649 } else {
650 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800651 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800652 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700653 }
654
655 return NO_ERROR;
656 }
David Chen0656b7a2017-09-13 15:53:39 -0700657 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700658 print_cmd_help(out);
659 return UNKNOWN_ERROR;
660}
661
Bookatzff71cad2018-09-20 17:17:49 -0700662status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700663 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800664 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700665 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800666 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700667 bool includeCurrentBucket = false;
Bookatz3e906582018-12-10 17:26:58 -0800668 bool eraseData = true;
Yao Chen729093d2017-10-16 10:33:26 -0700669 int uid;
670 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800671 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
672 proto = true;
673 argCount -= 1;
674 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700675 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
676 includeCurrentBucket = true;
677 argCount -= 1;
678 }
Bookatz3e906582018-12-10 17:26:58 -0800679 if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
680 eraseData = false;
681 argCount -= 1;
682 }
Yao Chen729093d2017-10-16 10:33:26 -0700683 if (argCount == 2) {
684 // Automatically pick the UID
685 uid = IPCThreadState::self()->getCallingUid();
Yao Chen5154a372017-10-30 22:57:06 -0700686 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700687 good = true;
688 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800689 good = getUidFromArgs(args, 1, uid);
690 if (!good) {
691 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
692 "other UIDs on eng or userdebug builds.\n");
Yao Chen729093d2017-10-16 10:33:26 -0700693 }
Bookatzd2386572018-12-14 15:53:14 -0800694 name.assign(args[2].c_str(), args[2].size());
Yao Chen729093d2017-10-16 10:33:26 -0700695 }
696 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800697 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800698 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000699 includeCurrentBucket, eraseData, ADB_DUMP,
700 NO_TIME_CONSTRAINTS,
701 &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800702 if (proto) {
703 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700704 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800705 }
706 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700707 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800708 }
Yao Chen729093d2017-10-16 10:33:26 -0700709 return android::OK;
710 } else {
711 // If arg parsing failed, print the help text and return an error.
712 print_cmd_help(out);
713 return UNKNOWN_ERROR;
714 }
715 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700716 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700717 return UNKNOWN_ERROR;
718 }
719}
720
Yao Chena80e5c02018-09-04 13:55:29 -0700721status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700722 int argCount = args.size();
723 bool proto = false;
724 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
725 proto = true;
726 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800727 }
Yao Chenb3561512017-11-21 18:07:17 -0800728 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700729 if (proto) {
730 vector<uint8_t> data;
731 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
732 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700733 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700734 }
735
736 } else {
737 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
738 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700739 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700740 mProcessor->GetMetricsSize(key));
741 }
742 statsdStats.dumpStats(out);
743 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800744 return NO_ERROR;
745}
746
Yao Chena80e5c02018-09-04 13:55:29 -0700747status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800748 if (args.size() > 1) {
749 string pkg;
750 pkg.assign(args[1].c_str(), args[1].size());
751 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700752 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800753 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700754 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800755 }
Yao Chena80e5c02018-09-04 13:55:29 -0700756 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800757 } else {
758 mUidMap->printUidMap(out);
759 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700760 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700761}
762
Yao Chena80e5c02018-09-04 13:55:29 -0700763status_t StatsService::cmd_write_data_to_disk(int out) {
764 dprintf(out, "Writing data to disk\n");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000765 mProcessor->WriteDataToDisk(ADB_DUMP, NO_TIME_CONSTRAINTS);
yro947fbce2017-11-15 22:50:23 -0800766 return NO_ERROR;
767}
768
Yao Chena80e5c02018-09-04 13:55:29 -0700769status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800770 bool good = false;
771 int32_t uid;
772 int32_t label;
773 int32_t state;
774 const int argCount = args.size();
775 if (argCount == 3) {
776 // Automatically pick the UID
777 uid = IPCThreadState::self()->getCallingUid();
778 label = atoi(args[1].c_str());
779 state = atoi(args[2].c_str());
780 good = true;
781 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800782 good = getUidFromArgs(args, 1, uid);
783 if (!good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700784 dprintf(out,
Bookatzd2386572018-12-14 15:53:14 -0800785 "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
786 "done for other UIDs on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800787 }
Bookatzd2386572018-12-14 15:53:14 -0800788 label = atoi(args[2].c_str());
789 state = atoi(args[3].c_str());
Bookatzb223c4e2018-02-01 15:35:04 -0800790 }
791 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700792 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
David Chen0b5c90c2018-01-25 16:51:49 -0800793 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800794 } else {
795 print_cmd_help(out);
796 return UNKNOWN_ERROR;
797 }
798 return NO_ERROR;
799}
800
Yao Chena80e5c02018-09-04 13:55:29 -0700801status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700802 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700803 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800804 if (mPullerManager->Pull(s, &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700805 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700806 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700807 }
Yao Chena80e5c02018-09-04 13:55:29 -0700808 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700809 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700810 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700811 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700812}
813
Yao Chena80e5c02018-09-04 13:55:29 -0700814status_t StatsService::cmd_remove_all_configs(int out) {
815 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800816 VLOG("StatsService::cmd_remove_all_configs was called");
817 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800818 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800819 return NO_ERROR;
820}
821
Yao Chena80e5c02018-09-04 13:55:29 -0700822status_t StatsService::cmd_dump_memory_info(int out) {
823 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800824 return NO_ERROR;
825}
826
Yao Chena80e5c02018-09-04 13:55:29 -0700827status_t StatsService::cmd_clear_puller_cache(int out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800828 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800829 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
830 ipc->getCallingPid(), ipc->getCallingUid());
Chenjie Yufa22d652018-02-05 14:37:48 -0800831 if (checkCallingPermission(String16(kPermissionDump))) {
Chenjie Yue2219202018-06-08 10:07:51 -0700832 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700833 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800834 return NO_ERROR;
835 } else {
836 return PERMISSION_DENIED;
837 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800838}
839
Yao Chena80e5c02018-09-04 13:55:29 -0700840status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Yao Chen876889c2018-05-02 11:16:16 -0700841 IPCThreadState* ipc = IPCThreadState::self();
842 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", ipc->getCallingPid(),
843 ipc->getCallingUid());
844 if (checkCallingPermission(String16(kPermissionDump))) {
845 bool enabled = true;
846 if (args.size() >= 2) {
847 enabled = atoi(args[1].c_str()) != 0;
848 }
849 mProcessor->setPrintLogs(enabled);
850 return NO_ERROR;
851 } else {
852 return PERMISSION_DENIED;
853 }
854}
855
Bookatzd2386572018-12-14 15:53:14 -0800856bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800857 return getUidFromString(args[uidArgIndex].c_str(), uid);
858}
859
860bool StatsService::getUidFromString(const char* s, int32_t& uid) {
Bookatzd2386572018-12-14 15:53:14 -0800861 if (*s == '\0') {
862 return false;
863 }
864 char* endc = NULL;
865 int64_t longUid = strtol(s, &endc, 0);
866 if (*endc != '\0') {
867 return false;
868 }
869 int32_t goodUid = static_cast<int32_t>(longUid);
870 if (longUid < 0 || static_cast<uint64_t>(longUid) != static_cast<uid_t>(goodUid)) {
871 return false; // It was not of uid_t type.
872 }
873 uid = goodUid;
874
875 int32_t callingUid = IPCThreadState::self()->getCallingUid();
876 return mEngBuild // UserDebug/EngBuild are allowed to impersonate uids.
877 || (callingUid == goodUid) // Anyone can 'impersonate' themselves.
878 || (callingUid == AID_ROOT && goodUid == AID_SHELL); // ROOT can impersonate SHELL.
879}
880
Dianne Hackborn3accca02013-09-20 09:32:11 -0700881Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int64_t>& version,
dwchen730403e2018-10-29 11:41:56 -0700882 const vector<String16>& version_string,
883 const vector<String16>& app,
884 const vector<String16>& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600885 ENFORCE_UID(AID_SYSTEM);
886
yro74fed972017-11-27 14:42:42 -0800887 VLOG("StatsService::informAllUidData was called");
dwchen730403e2018-10-29 11:41:56 -0700888 mUidMap->updateMap(getElapsedRealtimeNs(), uid, version, version_string, app, installer);
yro74fed972017-11-27 14:42:42 -0800889 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700890
891 return Status::ok();
892}
893
dwchen730403e2018-10-29 11:41:56 -0700894Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version,
895 const String16& version_string, const String16& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600896 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700897
Jeff Sharkey6b649252018-04-16 09:50:22 -0600898 VLOG("StatsService::informOnePackage was called");
dwchen730403e2018-10-29 11:41:56 -0700899 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version, version_string, installer);
David Chende701692017-10-05 13:16:02 -0700900 return Status::ok();
901}
902
903Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600904 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700905
Jeff Sharkey6b649252018-04-16 09:50:22 -0600906 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -0700907 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -0800908 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -0700909 return Status::ok();
910}
911
Yao Chenef99c4f2017-09-22 16:26:54 -0700912Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600913 ENFORCE_UID(AID_SYSTEM);
914
yro74fed972017-11-27 14:42:42 -0800915 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700916 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800917 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
918 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
919 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -0800920 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -0800921 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -0800922 } else {
923 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
924 }
Bookatz1b0b1142017-09-08 11:58:42 -0700925 return Status::ok();
926}
927
Yangster-mac932ecec2018-02-01 10:23:52 -0800928Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600929 ENFORCE_UID(AID_SYSTEM);
930
Yangster-mac932ecec2018-02-01 10:23:52 -0800931 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700932 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800933 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
934 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
935 if (alarmSet.size() > 0) {
936 VLOG("Found periodic alarm fired.");
937 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
938 } else {
939 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
940 }
941 return Status::ok();
942}
943
Yao Chenef99c4f2017-09-22 16:26:54 -0700944Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600945 ENFORCE_UID(AID_SYSTEM);
946
yro74fed972017-11-27 14:42:42 -0800947 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700948 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -0800949 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700950 return Status::ok();
951}
952
Yao Chenef99c4f2017-09-22 16:26:54 -0700953Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600954 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700955
956 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800957 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -0700958 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700959 return Status::ok();
960}
961
Yangster-mac892f3d32018-05-02 14:16:48 -0700962Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600963 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -0700964 VLOG("StatsService::informDeviceShutdown");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000965 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN, FAST);
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800966 mProcessor->WriteMetricsActivationToDisk(getElapsedRealtimeNs());
yro947fbce2017-11-15 22:50:23 -0800967 return Status::ok();
968}
969
Yao Chenef99c4f2017-09-22 16:26:54 -0700970void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -0700971 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
972 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -0800973 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -0700974 statsCompanion->statsdReady();
975 } else {
yro74fed972017-11-27 14:42:42 -0800976 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -0700977 }
978}
979
Yao Chenef99c4f2017-09-22 16:26:54 -0700980Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600981 ENFORCE_UID(AID_SYSTEM);
982
yro74fed972017-11-27 14:42:42 -0800983 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -0700984 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
985 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700986 return Status::fromExceptionCode(
987 Status::EX_NULL_POINTER,
988 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700989 }
yro74fed972017-11-27 14:42:42 -0800990 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -0700991 IInterface::asBinder(statsCompanion)->linkToDeath(this);
Chenjie Yue2219202018-06-08 10:07:51 -0700992 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -0800993 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
994 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -0800995 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -0700996 return Status::ok();
997}
998
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700999void StatsService::Startup() {
1000 mConfigManager->Startup();
Chenjie Yuc7939cb2019-02-04 17:25:45 -08001001 mProcessor->LoadMetricsActivationFromDisk();
Bookatz906a35c2017-09-20 15:26:44 -07001002}
1003
Yangster-mac97e7d202018-10-09 11:05:39 -07001004void StatsService::Terminate() {
1005 ALOGI("StatsService::Terminating");
1006 if (mProcessor != nullptr) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001007 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED, FAST);
Yangster-mac97e7d202018-10-09 11:05:39 -07001008 }
1009}
1010
Yao Chen3ff3a492018-08-06 16:17:37 -07001011void StatsService::OnLogEvent(LogEvent* event) {
1012 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -07001013 if (mShellSubscriber != nullptr) {
1014 mShellSubscriber->onLogEvent(*event);
1015 }
Bookatz906a35c2017-09-20 15:26:44 -07001016}
1017
Jeff Sharkey6b649252018-04-16 09:50:22 -06001018Status StatsService::getData(int64_t key, const String16& packageName, vector<uint8_t>* output) {
1019 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1020
David Chenadaf8b32017-11-03 15:42:08 -07001021 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -08001022 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001023 ConfigKey configKey(ipc->getCallingUid(), key);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001024 // The dump latency does not matter here since we do not include the current bucket, we do not
1025 // need to pull any new data anyhow.
David Chen56ae0d92018-05-11 16:00:22 -07001026 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001027 true /* erase_data */, GET_DATA_CALLED, FAST, output);
Bookatz4f716292018-04-10 17:15:12 -07001028 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001029}
1030
Jeff Sharkey6b649252018-04-16 09:50:22 -06001031Status StatsService::getMetadata(const String16& packageName, vector<uint8_t>* output) {
1032 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1033
David Chen2e8f3802017-11-22 10:56:48 -08001034 IPCThreadState* ipc = IPCThreadState::self();
1035 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
1036 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001037 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
1038 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -08001039}
1040
Jeff Sharkey6b649252018-04-16 09:50:22 -06001041Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
1042 const String16& packageName) {
1043 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1044
David Chenadaf8b32017-11-03 15:42:08 -07001045 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -07001046 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -08001047 return Status::ok();
1048 } else {
Bookatz4f716292018-04-10 17:15:12 -07001049 ALOGE("Could not parse malformatted StatsdConfig");
1050 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
1051 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -08001052 }
1053}
1054
David Chen9fdd4032018-03-20 14:38:56 -07001055bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
1056 ConfigKey configKey(uid, key);
1057 StatsdConfig cfg;
1058 if (config.size() > 0) { // If the config is empty, skip parsing.
1059 if (!cfg.ParseFromArray(&config[0], config.size())) {
1060 return false;
1061 }
1062 }
1063 mConfigManager->UpdateConfig(configKey, cfg);
1064 return true;
1065}
1066
Jeff Sharkey6b649252018-04-16 09:50:22 -06001067Status StatsService::removeDataFetchOperation(int64_t key, const String16& packageName) {
1068 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1069
Bookatz4f716292018-04-10 17:15:12 -07001070 IPCThreadState* ipc = IPCThreadState::self();
1071 ConfigKey configKey(ipc->getCallingUid(), key);
1072 mConfigManager->RemoveConfigReceiver(configKey);
1073 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -08001074}
1075
Jeff Sharkey6b649252018-04-16 09:50:22 -06001076Status StatsService::setDataFetchOperation(int64_t key,
1077 const sp<android::IBinder>& intentSender,
1078 const String16& packageName) {
1079 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1080
Bookatz4f716292018-04-10 17:15:12 -07001081 IPCThreadState* ipc = IPCThreadState::self();
1082 ConfigKey configKey(ipc->getCallingUid(), key);
1083 mConfigManager->SetConfigReceiver(configKey, intentSender);
David Chen48944902018-05-03 10:29:11 -07001084 if (StorageManager::hasConfigMetricsReport(configKey)) {
1085 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
1086 configKey.ToString().c_str());
1087 mProcessor->noteOnDiskData(configKey);
1088 }
Bookatz4f716292018-04-10 17:15:12 -07001089 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001090}
1091
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001092Status StatsService::setActiveConfigsChangedOperation(const sp<android::IBinder>& intentSender,
1093 const String16& packageName,
1094 vector<int64_t>* output) {
1095 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1096
1097 IPCThreadState* ipc = IPCThreadState::self();
Tej Singh6ede28b2019-01-29 17:06:54 -08001098 int uid = ipc->getCallingUid();
1099 mConfigManager->SetActiveConfigsChangedReceiver(uid, intentSender);
1100 if (output != nullptr) {
1101 mProcessor->GetActiveConfigs(uid, *output);
1102 } else {
1103 ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
1104 }
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001105 return Status::ok();
1106}
1107
1108Status StatsService::removeActiveConfigsChangedOperation(const String16& packageName) {
1109 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1110
1111 IPCThreadState* ipc = IPCThreadState::self();
1112 mConfigManager->RemoveActiveConfigsChangedReceiver(ipc->getCallingUid());
1113 return Status::ok();
1114}
1115
Jeff Sharkey6b649252018-04-16 09:50:22 -06001116Status StatsService::removeConfiguration(int64_t key, const String16& packageName) {
1117 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1118
Bookatz4f716292018-04-10 17:15:12 -07001119 IPCThreadState* ipc = IPCThreadState::self();
1120 ConfigKey configKey(ipc->getCallingUid(), key);
1121 mConfigManager->RemoveConfig(configKey);
1122 SubscriberReporter::getInstance().removeConfig(configKey);
1123 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001124}
1125
Bookatzc6977972018-01-16 16:55:05 -08001126Status StatsService::setBroadcastSubscriber(int64_t configId,
1127 int64_t subscriberId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001128 const sp<android::IBinder>& intentSender,
1129 const String16& packageName) {
1130 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1131
Bookatzc6977972018-01-16 16:55:05 -08001132 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001133 IPCThreadState* ipc = IPCThreadState::self();
1134 ConfigKey configKey(ipc->getCallingUid(), configId);
1135 SubscriberReporter::getInstance()
1136 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
1137 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001138}
1139
1140Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001141 int64_t subscriberId,
1142 const String16& packageName) {
1143 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1144
Bookatzc6977972018-01-16 16:55:05 -08001145 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001146 IPCThreadState* ipc = IPCThreadState::self();
1147 ConfigKey configKey(ipc->getCallingUid(), configId);
1148 SubscriberReporter::getInstance()
1149 .unsetBroadcastSubscriber(configKey, subscriberId);
1150 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001151}
1152
yrobe6d7f92018-05-04 13:02:53 -07001153Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
1154 // Permission check not necessary as it's meant for applications to write to
1155 // statsd.
1156 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
1157 IPCThreadState::self()->getCallingUid(), label,
1158 state);
1159 return Status::ok();
1160}
1161
Tej Singha0c89dd2019-01-25 16:39:18 -08001162Status StatsService::registerPullerCallback(int32_t atomTag,
1163 const sp<android::os::IStatsPullerCallback>& pullerCallback,
1164 const String16& packageName) {
1165 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1166
1167 VLOG("StatsService::registerPullerCallback called.");
1168 mPullerManager->RegisterPullerCallback(atomTag, pullerCallback);
1169 return Status::ok();
1170}
1171
1172Status StatsService::unregisterPullerCallback(int32_t atomTag, const String16& packageName) {
1173 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1174
1175 VLOG("StatsService::unregisterPullerCallback called.");
1176 mPullerManager->UnregisterPullerCallback(atomTag);
1177 return Status::ok();
1178}
1179
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001180Status StatsService::sendBinaryPushStateChangedAtom(const android::String16& trainName,
1181 int64_t trainVersionCode, int options,
1182 int32_t state,
1183 const std::vector<int64_t>& experimentIds) {
1184 uid_t uid = IPCThreadState::self()->getCallingUid();
1185 // For testing
1186 if (uid == AID_ROOT || uid == AID_SYSTEM || uid == AID_SHELL) {
1187 return ok();
1188 }
1189
1190 // Caller must be granted these permissions
1191 if (!checkCallingPermission(String16(kPermissionDump))) {
1192 return exception(binder::Status::EX_SECURITY,
1193 StringPrintf("UID %d lacks permission %s", uid, kPermissionDump));
1194 }
1195 if (!checkCallingPermission(String16(kPermissionUsage))) {
1196 return exception(binder::Status::EX_SECURITY,
1197 StringPrintf("UID %d lacks permission %s", uid, kPermissionUsage));
1198 }
1199 // TODO: add verifier permission
1200
1201 userid_t userId = multiuser_get_user_id(uid);
1202
Chenjie Yua2fc1242019-02-22 14:09:59 -08001203 bool requiresStaging = options & IStatsManager::FLAG_REQUIRE_STAGING;
1204 bool rollbackEnabled = options & IStatsManager::FLAG_ROLLBACK_ENABLED;
1205 bool requiresLowLatencyMonitor = options & IStatsManager::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001206
1207 ProtoOutputStream proto;
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001208 for (const auto& expId : experimentIds) {
1209 proto.write(FIELD_TYPE_INT64 | FIELD_COUNT_REPEATED | FIELD_ID_EXPERIMENT_ID,
1210 (long long)expId);
1211 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001212
1213 vector<uint8_t> buffer;
1214 buffer.resize(proto.size());
1215 size_t pos = 0;
1216 auto iter = proto.data();
1217 while (iter.readBuffer() != NULL) {
1218 size_t toRead = iter.currentToRead();
1219 std::memcpy(&(buffer[pos]), iter.readBuffer(), toRead);
1220 pos += toRead;
1221 iter.rp()->move(toRead);
1222 }
1223 LogEvent event(std::string(String8(trainName).string()), trainVersionCode, requiresStaging,
1224 rollbackEnabled, requiresLowLatencyMonitor, state, buffer, userId);
1225 mProcessor->OnLogEvent(&event);
1226 StorageManager::writeTrainInfo(trainVersionCode, buffer);
1227 return Status::ok();
1228}
1229
Howard Roa46b6582018-09-18 16:45:02 -07001230hardware::Return<void> StatsService::reportSpeakerImpedance(
1231 const SpeakerImpedance& speakerImpedance) {
1232 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), speakerImpedance);
1233 mProcessor->OnLogEvent(&event);
1234
1235 return hardware::Void();
1236}
1237
1238hardware::Return<void> StatsService::reportHardwareFailed(const HardwareFailed& hardwareFailed) {
1239 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), hardwareFailed);
1240 mProcessor->OnLogEvent(&event);
1241
1242 return hardware::Void();
1243}
1244
1245hardware::Return<void> StatsService::reportPhysicalDropDetected(
1246 const PhysicalDropDetected& physicalDropDetected) {
1247 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), physicalDropDetected);
1248 mProcessor->OnLogEvent(&event);
1249
1250 return hardware::Void();
1251}
1252
1253hardware::Return<void> StatsService::reportChargeCycles(const ChargeCycles& chargeCycles) {
1254 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), chargeCycles);
1255 mProcessor->OnLogEvent(&event);
1256
1257 return hardware::Void();
1258}
1259
1260hardware::Return<void> StatsService::reportBatteryHealthSnapshot(
1261 const BatteryHealthSnapshotArgs& batteryHealthSnapshotArgs) {
1262 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(),
1263 batteryHealthSnapshotArgs);
1264 mProcessor->OnLogEvent(&event);
1265
1266 return hardware::Void();
1267}
1268
1269hardware::Return<void> StatsService::reportSlowIo(const SlowIo& slowIo) {
1270 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), slowIo);
1271 mProcessor->OnLogEvent(&event);
1272
1273 return hardware::Void();
1274}
1275
1276hardware::Return<void> StatsService::reportBatteryCausedShutdown(
1277 const BatteryCausedShutdown& batteryCausedShutdown) {
1278 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), batteryCausedShutdown);
1279 mProcessor->OnLogEvent(&event);
1280
1281 return hardware::Void();
1282}
1283
Maggie Whitefc1aa592018-11-28 21:55:23 -08001284hardware::Return<void> StatsService::reportUsbPortOverheatEvent(
1285 const UsbPortOverheatEvent& usbPortOverheatEvent) {
1286 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), usbPortOverheatEvent);
1287 mProcessor->OnLogEvent(&event);
1288
1289 return hardware::Void();
1290}
1291
Carter Hsub8fd1e92019-01-11 15:24:45 +08001292hardware::Return<void> StatsService::reportSpeechDspStat(
1293 const SpeechDspStat& speechDspStat) {
1294 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), speechDspStat);
1295 mProcessor->OnLogEvent(&event);
1296
1297 return hardware::Void();
1298}
1299
Maggie White58174da2019-01-18 15:23:35 -08001300hardware::Return<void> StatsService::reportVendorAtom(const VendorAtom& vendorAtom) {
1301 std::string reverseDomainName = (std::string) vendorAtom.reverseDomainName;
1302 if (vendorAtom.atomId < 100000 || vendorAtom.atomId >= 200000) {
1303 ALOGE("Atom ID %ld is not a valid vendor atom ID", (long) vendorAtom.atomId);
1304 return hardware::Void();
1305 }
1306 if (reverseDomainName.length() > 50) {
1307 ALOGE("Vendor atom reverse domain name %s is too long.", reverseDomainName.c_str());
1308 return hardware::Void();
1309 }
1310 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), vendorAtom);
1311 mProcessor->OnLogEvent(&event);
1312
1313 return hardware::Void();
1314}
1315
David Chen1d7b0cd2017-11-15 14:20:04 -08001316void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001317 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001318 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1319 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001320 ALOGW("Reset statsd upon system server restarts.");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001321 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED, FAST);
Yangster-mac892f3d32018-05-02 14:16:48 -07001322 mProcessor->resetConfigs();
1323 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001324 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1325 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
1326 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001327 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001328}
1329
Yao Chenef99c4f2017-09-22 16:26:54 -07001330} // namespace statsd
1331} // namespace os
1332} // namespace android