blob: c542b6215c884a7252c4bd8303f5ff6e012b6f93 [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 */,
316 ADB_DUMP, &proto);
317 proto.end(reportsListToken);
318 proto.flush(out);
Bookatzc71d9012018-12-19 12:28:38 -0800319 proto.clear();
Bookatzff71cad2018-09-20 17:17:49 -0700320 }
321}
322
323/**
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700324 * Implementation of the adb shell cmd stats command.
325 */
Yao Chena80e5c02018-09-04 13:55:29 -0700326status_t StatsService::command(int in, int out, int err, Vector<String8>& args,
327 sp<IResultReceiver> resultReceiver) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600328 uid_t uid = IPCThreadState::self()->getCallingUid();
329 if (uid != AID_ROOT && uid != AID_SHELL) {
330 return PERMISSION_DENIED;
331 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700332
333 const int argCount = args.size();
334 if (argCount >= 1) {
335 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700336 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700337 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700338 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700339
David Chende701692017-10-05 13:16:02 -0700340 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800341 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700342 }
Yao Chen729093d2017-10-16 10:33:26 -0700343
344 if (!args[0].compare(String8("dump-report"))) {
Bookatzff71cad2018-09-20 17:17:49 -0700345 return cmd_dump_report(out, args);
Yao Chen729093d2017-10-16 10:33:26 -0700346 }
David Chen1481fe12017-10-16 13:16:34 -0700347
348 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
349 return cmd_print_pulled_metrics(out, args);
350 }
David Chenadaf8b32017-11-03 15:42:08 -0700351
352 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800353 return cmd_trigger_broadcast(out, args);
354 }
355
356 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800357 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700358 }
yro87d983c2017-11-14 21:31:43 -0800359
Yao Chen8d9989b2017-11-18 18:54:50 -0800360 if (!args[0].compare(String8("meminfo"))) {
361 return cmd_dump_memory_info(out);
362 }
yro947fbce2017-11-15 22:50:23 -0800363
364 if (!args[0].compare(String8("write-to-disk"))) {
365 return cmd_write_data_to_disk(out);
366 }
Bookatzb223c4e2018-02-01 15:35:04 -0800367
David Chen0b5c90c2018-01-25 16:51:49 -0800368 if (!args[0].compare(String8("log-app-breadcrumb"))) {
369 return cmd_log_app_breadcrumb(out, args);
Bookatzb223c4e2018-02-01 15:35:04 -0800370 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800371
372 if (!args[0].compare(String8("clear-puller-cache"))) {
373 return cmd_clear_puller_cache(out);
374 }
Yao Chen876889c2018-05-02 11:16:16 -0700375
376 if (!args[0].compare(String8("print-logs"))) {
377 return cmd_print_logs(out, args);
378 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800379 if (!args[0].compare(String8("send-active-configs"))) {
380 return cmd_trigger_active_config_broadcast(out, args);
381 }
Yao Chena80e5c02018-09-04 13:55:29 -0700382 if (!args[0].compare(String8("data-subscribe"))) {
383 if (mShellSubscriber == nullptr) {
Yao Chen41e606c2018-10-05 15:54:11 -0700384 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
Yao Chena80e5c02018-09-04 13:55:29 -0700385 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800386 int timeoutSec = -1;
387 if (argCount >= 2) {
388 timeoutSec = atoi(args[1].c_str());
389 }
390 mShellSubscriber->startNewSubscription(in, out, resultReceiver, timeoutSec);
Yao Chena80e5c02018-09-04 13:55:29 -0700391 return NO_ERROR;
392 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700393 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700394
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700395 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700396 return NO_ERROR;
397}
398
Yao Chena80e5c02018-09-04 13:55:29 -0700399void StatsService::print_cmd_help(int out) {
400 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700401 "usage: adb shell cmd stats print-stats-log [tag_required] "
402 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700403 dprintf(out, "\n");
404 dprintf(out, "\n");
405 dprintf(out, "usage: adb shell cmd stats meminfo\n");
406 dprintf(out, "\n");
407 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
408 dprintf(out, " # adb shell stop\n");
409 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
410 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
411 dprintf(out, " # adb shell start\n");
412 dprintf(out, "\n");
413 dprintf(out, "\n");
414 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
415 dprintf(out, "\n");
416 dprintf(out, " Prints the UID, app name, version mapping.\n");
417 dprintf(out, " PKG Optional package name to print the uids of the package\n");
418 dprintf(out, "\n");
419 dprintf(out, "\n");
420 dprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
421 dprintf(out, "\n");
422 dprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
423 dprintf(out, "\n");
424 dprintf(out, "\n");
425 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
426 dprintf(out, "\n");
427 dprintf(out, " Flushes all data on memory to disk.\n");
428 dprintf(out, "\n");
429 dprintf(out, "\n");
430 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
431 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
432 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
433 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
434 dprintf(out, " uid is used.\n");
435 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
436 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
437 dprintf(out, "\n");
438 dprintf(out, "\n");
439 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
440 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
441 dprintf(out, "\n");
442 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
443 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
444 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
445 dprintf(out, "\n");
446 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
447 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
448 dprintf(out, " uid is used.\n");
449 dprintf(out, " NAME The per-uid name to use\n");
450 dprintf(out, "\n");
451 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
452 dprintf(out, "\n be removed from memory and disk!\n");
453 dprintf(out, "\n");
454 dprintf(out,
Bookatz3e906582018-12-10 17:26:58 -0800455 "usage: adb shell cmd stats dump-report [UID] NAME [--keep_data] "
456 "[--include_current_bucket] [--proto]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700457 dprintf(out, " Dump all metric data for a configuration.\n");
458 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
459 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
460 dprintf(out, " calling uid is used.\n");
461 dprintf(out, " NAME The name of the configuration\n");
Bookatz3e906582018-12-10 17:26:58 -0800462 dprintf(out, " --keep_data Do NOT erase the data upon dumping it.\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700463 dprintf(out, " --proto Print proto binary.\n");
464 dprintf(out, "\n");
465 dprintf(out, "\n");
466 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
467 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
468 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
469 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
470 dprintf(out, " calling uid is used.\n");
471 dprintf(out, " NAME The name of the configuration\n");
472 dprintf(out, "\n");
473 dprintf(out, "\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800474 dprintf(out,
475 "usage: adb shell cmd stats send-active-configs [--uid=UID] [--configs] "
476 "[NAME1] [NAME2] [NAME3..]\n");
477 dprintf(out, " Send a broadcast that informs the subscriber of the current active configs.\n");
478 dprintf(out, " --uid=UID The uid of the configurations. It is only possible to pass\n");
479 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
480 dprintf(out, " calling uid is used.\n");
481 dprintf(out, " --configs Send the list of configs in the name list instead of\n");
482 dprintf(out, " the currently active configs\n");
483 dprintf(out, " NAME LIST List of configuration names to be included in the broadcast.\n");
484
485 dprintf(out, "\n");
486 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700487 dprintf(out, "usage: adb shell cmd stats print-stats\n");
488 dprintf(out, " Prints some basic stats.\n");
489 dprintf(out, " --proto Print proto binary instead of string format.\n");
490 dprintf(out, "\n");
491 dprintf(out, "\n");
492 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
493 dprintf(out, " Clear cached puller data.\n");
494 dprintf(out, "\n");
495 dprintf(out, "usage: adb shell cmd stats print-logs\n");
496 dprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700497}
498
Yao Chena80e5c02018-09-04 13:55:29 -0700499status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800500 string name;
501 bool good = false;
502 int uid;
503 const int argCount = args.size();
504 if (argCount == 2) {
505 // Automatically pick the UID
506 uid = IPCThreadState::self()->getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800507 name.assign(args[1].c_str(), args[1].size());
508 good = true;
509 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800510 good = getUidFromArgs(args, 1, uid);
511 if (!good) {
512 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
513 "other UIDs on eng or userdebug builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800514 }
Bookatzd2386572018-12-14 15:53:14 -0800515 name.assign(args[2].c_str(), args[2].size());
David Chen1d7b0cd2017-11-15 14:20:04 -0800516 }
517 if (!good) {
518 print_cmd_help(out);
519 return UNKNOWN_ERROR;
520 }
David Chend37bc232018-04-12 18:05:11 -0700521 ConfigKey key(uid, StrToInt64(name));
522 auto receiver = mConfigManager->GetConfigReceiver(key);
yro4d889e62017-11-17 15:44:48 -0800523 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen661f7912018-01-22 17:46:24 -0800524 if (sc == nullptr) {
525 VLOG("Could not access statsCompanion");
526 } else if (receiver == nullptr) {
527 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str())
528 } else {
David Chend37bc232018-04-12 18:05:11 -0700529 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
yro74fed972017-11-27 14:42:42 -0800530 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
531 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800532 }
533
David Chenadaf8b32017-11-03 15:42:08 -0700534 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700535}
536
Tej Singh6ede28b2019-01-29 17:06:54 -0800537status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
538 const int argCount = args.size();
539 int uid;
540 vector<int64_t> configIds;
541 if (argCount == 1) {
542 // Automatically pick the uid and send a broadcast that has no active configs.
543 uid = IPCThreadState::self()->getCallingUid();
544 mProcessor->GetActiveConfigs(uid, configIds);
545 } else {
546 int curArg = 1;
547 if(args[curArg].find("--uid=") == 0) {
548 string uidArgStr(args[curArg].c_str());
549 string uidStr = uidArgStr.substr(6);
550 if (!getUidFromString(uidStr.c_str(), uid)) {
551 dprintf(out, "Invalid UID. Note that the config can only be set for "
552 "other UIDs on eng or userdebug builds.\n");
553 return UNKNOWN_ERROR;
554 }
555 curArg++;
556 } else {
557 uid = IPCThreadState::self()->getCallingUid();
558 }
559 if (curArg == argCount || args[curArg] != "--configs") {
560 VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
561 mProcessor->GetActiveConfigs(uid, configIds);
562 } else {
563 // Flag specified, use the given list of configs.
564 curArg++;
565 for (int i = curArg; i < argCount; i++) {
566 char* endp;
567 int64_t configID = strtoll(args[i].c_str(), &endp, 10);
568 if (endp == args[i].c_str() || *endp != '\0') {
569 dprintf(out, "Error parsing config ID.\n");
570 return UNKNOWN_ERROR;
571 }
572 VLOG("Adding config id %ld", static_cast<long>(configID));
573 configIds.push_back(configID);
574 }
575 }
576 }
577 auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
578 sp<IStatsCompanionService> sc = getStatsCompanionService();
579 if (sc == nullptr) {
580 VLOG("Could not access statsCompanion");
581 } else if (receiver == nullptr) {
582 VLOG("Could not find receiver for uid %d", uid);
583 } else {
584 sc->sendActiveConfigsChangedBroadcast(receiver, configIds);
585 VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
586 }
587 return NO_ERROR;
588}
589
Yao Chena80e5c02018-09-04 13:55:29 -0700590status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700591 const int argCount = args.size();
592 if (argCount >= 2) {
593 if (args[1] == "update" || args[1] == "remove") {
594 bool good = false;
595 int uid = -1;
596 string name;
597
598 if (argCount == 3) {
599 // Automatically pick the UID
600 uid = IPCThreadState::self()->getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700601 name.assign(args[2].c_str(), args[2].size());
602 good = true;
603 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800604 good = getUidFromArgs(args, 2, uid);
605 if (!good) {
606 dprintf(err, "Invalid UID. Note that the config can only be set for "
607 "other UIDs on eng or userdebug builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700608 }
Bookatzd2386572018-12-14 15:53:14 -0800609 name.assign(args[3].c_str(), args[3].size());
yroe5f82922018-01-22 18:37:27 -0800610 } else if (argCount == 2 && args[1] == "remove") {
611 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700612 }
613
614 if (!good) {
615 // If arg parsing failed, print the help text and return an error.
616 print_cmd_help(out);
617 return UNKNOWN_ERROR;
618 }
619
620 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800621 char* endp;
622 int64_t configID = strtoll(name.c_str(), &endp, 10);
623 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700624 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800625 return UNKNOWN_ERROR;
626 }
627
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700628 // Read stream into buffer.
629 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700630 if (!android::base::ReadFdToString(in, &buffer)) {
631 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700632 return UNKNOWN_ERROR;
633 }
634
635 // Parse buffer.
636 StatsdConfig config;
637 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700638 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700639 return UNKNOWN_ERROR;
640 }
641
642 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800643 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700644 } else {
yro74fed972017-11-27 14:42:42 -0800645 if (argCount == 2) {
646 cmd_remove_all_configs(out);
647 } else {
648 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800649 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800650 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700651 }
652
653 return NO_ERROR;
654 }
David Chen0656b7a2017-09-13 15:53:39 -0700655 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700656 print_cmd_help(out);
657 return UNKNOWN_ERROR;
658}
659
Bookatzff71cad2018-09-20 17:17:49 -0700660status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700661 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800662 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700663 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800664 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700665 bool includeCurrentBucket = false;
Bookatz3e906582018-12-10 17:26:58 -0800666 bool eraseData = true;
Yao Chen729093d2017-10-16 10:33:26 -0700667 int uid;
668 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800669 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
670 proto = true;
671 argCount -= 1;
672 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700673 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
674 includeCurrentBucket = true;
675 argCount -= 1;
676 }
Bookatz3e906582018-12-10 17:26:58 -0800677 if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
678 eraseData = false;
679 argCount -= 1;
680 }
Yao Chen729093d2017-10-16 10:33:26 -0700681 if (argCount == 2) {
682 // Automatically pick the UID
683 uid = IPCThreadState::self()->getCallingUid();
Yao Chen5154a3792017-10-30 22:57:06 -0700684 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700685 good = true;
686 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800687 good = getUidFromArgs(args, 1, uid);
688 if (!good) {
689 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
690 "other UIDs on eng or userdebug builds.\n");
Yao Chen729093d2017-10-16 10:33:26 -0700691 }
Bookatzd2386572018-12-14 15:53:14 -0800692 name.assign(args[2].c_str(), args[2].size());
Yao Chen729093d2017-10-16 10:33:26 -0700693 }
694 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800695 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800696 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Bookatz3e906582018-12-10 17:26:58 -0800697 includeCurrentBucket, eraseData, ADB_DUMP, &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800698 if (proto) {
699 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700700 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800701 }
702 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700703 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800704 }
Yao Chen729093d2017-10-16 10:33:26 -0700705 return android::OK;
706 } else {
707 // If arg parsing failed, print the help text and return an error.
708 print_cmd_help(out);
709 return UNKNOWN_ERROR;
710 }
711 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700712 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700713 return UNKNOWN_ERROR;
714 }
715}
716
Yao Chena80e5c02018-09-04 13:55:29 -0700717status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700718 int argCount = args.size();
719 bool proto = false;
720 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
721 proto = true;
722 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800723 }
Yao Chenb3561512017-11-21 18:07:17 -0800724 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700725 if (proto) {
726 vector<uint8_t> data;
727 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
728 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700729 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700730 }
731
732 } else {
733 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
734 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700735 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700736 mProcessor->GetMetricsSize(key));
737 }
738 statsdStats.dumpStats(out);
739 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800740 return NO_ERROR;
741}
742
Yao Chena80e5c02018-09-04 13:55:29 -0700743status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800744 if (args.size() > 1) {
745 string pkg;
746 pkg.assign(args[1].c_str(), args[1].size());
747 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700748 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800749 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700750 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800751 }
Yao Chena80e5c02018-09-04 13:55:29 -0700752 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800753 } else {
754 mUidMap->printUidMap(out);
755 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700756 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700757}
758
Yao Chena80e5c02018-09-04 13:55:29 -0700759status_t StatsService::cmd_write_data_to_disk(int out) {
760 dprintf(out, "Writing data to disk\n");
Yangster-mac892f3d32018-05-02 14:16:48 -0700761 mProcessor->WriteDataToDisk(ADB_DUMP);
yro947fbce2017-11-15 22:50:23 -0800762 return NO_ERROR;
763}
764
Yao Chena80e5c02018-09-04 13:55:29 -0700765status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800766 bool good = false;
767 int32_t uid;
768 int32_t label;
769 int32_t state;
770 const int argCount = args.size();
771 if (argCount == 3) {
772 // Automatically pick the UID
773 uid = IPCThreadState::self()->getCallingUid();
774 label = atoi(args[1].c_str());
775 state = atoi(args[2].c_str());
776 good = true;
777 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800778 good = getUidFromArgs(args, 1, uid);
779 if (!good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700780 dprintf(out,
Bookatzd2386572018-12-14 15:53:14 -0800781 "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
782 "done for other UIDs on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800783 }
Bookatzd2386572018-12-14 15:53:14 -0800784 label = atoi(args[2].c_str());
785 state = atoi(args[3].c_str());
Bookatzb223c4e2018-02-01 15:35:04 -0800786 }
787 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700788 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
David Chen0b5c90c2018-01-25 16:51:49 -0800789 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800790 } else {
791 print_cmd_help(out);
792 return UNKNOWN_ERROR;
793 }
794 return NO_ERROR;
795}
796
Yao Chena80e5c02018-09-04 13:55:29 -0700797status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700798 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700799 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800800 if (mPullerManager->Pull(s, &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700801 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700802 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700803 }
Yao Chena80e5c02018-09-04 13:55:29 -0700804 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700805 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700806 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700807 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700808}
809
Yao Chena80e5c02018-09-04 13:55:29 -0700810status_t StatsService::cmd_remove_all_configs(int out) {
811 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800812 VLOG("StatsService::cmd_remove_all_configs was called");
813 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800814 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800815 return NO_ERROR;
816}
817
Yao Chena80e5c02018-09-04 13:55:29 -0700818status_t StatsService::cmd_dump_memory_info(int out) {
819 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800820 return NO_ERROR;
821}
822
Yao Chena80e5c02018-09-04 13:55:29 -0700823status_t StatsService::cmd_clear_puller_cache(int out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800824 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800825 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
826 ipc->getCallingPid(), ipc->getCallingUid());
Chenjie Yufa22d652018-02-05 14:37:48 -0800827 if (checkCallingPermission(String16(kPermissionDump))) {
Chenjie Yue2219202018-06-08 10:07:51 -0700828 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700829 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800830 return NO_ERROR;
831 } else {
832 return PERMISSION_DENIED;
833 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800834}
835
Yao Chena80e5c02018-09-04 13:55:29 -0700836status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Yao Chen876889c2018-05-02 11:16:16 -0700837 IPCThreadState* ipc = IPCThreadState::self();
838 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", ipc->getCallingPid(),
839 ipc->getCallingUid());
840 if (checkCallingPermission(String16(kPermissionDump))) {
841 bool enabled = true;
842 if (args.size() >= 2) {
843 enabled = atoi(args[1].c_str()) != 0;
844 }
845 mProcessor->setPrintLogs(enabled);
846 return NO_ERROR;
847 } else {
848 return PERMISSION_DENIED;
849 }
850}
851
Bookatzd2386572018-12-14 15:53:14 -0800852bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800853 return getUidFromString(args[uidArgIndex].c_str(), uid);
854}
855
856bool StatsService::getUidFromString(const char* s, int32_t& uid) {
Bookatzd2386572018-12-14 15:53:14 -0800857 if (*s == '\0') {
858 return false;
859 }
860 char* endc = NULL;
861 int64_t longUid = strtol(s, &endc, 0);
862 if (*endc != '\0') {
863 return false;
864 }
865 int32_t goodUid = static_cast<int32_t>(longUid);
866 if (longUid < 0 || static_cast<uint64_t>(longUid) != static_cast<uid_t>(goodUid)) {
867 return false; // It was not of uid_t type.
868 }
869 uid = goodUid;
870
871 int32_t callingUid = IPCThreadState::self()->getCallingUid();
872 return mEngBuild // UserDebug/EngBuild are allowed to impersonate uids.
873 || (callingUid == goodUid) // Anyone can 'impersonate' themselves.
874 || (callingUid == AID_ROOT && goodUid == AID_SHELL); // ROOT can impersonate SHELL.
875}
876
Dianne Hackborn3accca02013-09-20 09:32:11 -0700877Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int64_t>& version,
dwchen730403e2018-10-29 11:41:56 -0700878 const vector<String16>& version_string,
879 const vector<String16>& app,
880 const vector<String16>& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600881 ENFORCE_UID(AID_SYSTEM);
882
yro74fed972017-11-27 14:42:42 -0800883 VLOG("StatsService::informAllUidData was called");
dwchen730403e2018-10-29 11:41:56 -0700884 mUidMap->updateMap(getElapsedRealtimeNs(), uid, version, version_string, app, installer);
yro74fed972017-11-27 14:42:42 -0800885 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700886
887 return Status::ok();
888}
889
dwchen730403e2018-10-29 11:41:56 -0700890Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version,
891 const String16& version_string, const String16& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600892 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700893
Jeff Sharkey6b649252018-04-16 09:50:22 -0600894 VLOG("StatsService::informOnePackage was called");
dwchen730403e2018-10-29 11:41:56 -0700895 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version, version_string, installer);
David Chende701692017-10-05 13:16:02 -0700896 return Status::ok();
897}
898
899Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600900 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700901
Jeff Sharkey6b649252018-04-16 09:50:22 -0600902 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -0700903 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -0800904 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -0700905 return Status::ok();
906}
907
Yao Chenef99c4f2017-09-22 16:26:54 -0700908Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600909 ENFORCE_UID(AID_SYSTEM);
910
yro74fed972017-11-27 14:42:42 -0800911 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700912 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800913 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
914 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
915 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -0800916 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -0800917 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -0800918 } else {
919 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
920 }
Bookatz1b0b1142017-09-08 11:58:42 -0700921 return Status::ok();
922}
923
Yangster-mac932ecec2018-02-01 10:23:52 -0800924Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600925 ENFORCE_UID(AID_SYSTEM);
926
Yangster-mac932ecec2018-02-01 10:23:52 -0800927 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700928 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800929 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
930 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
931 if (alarmSet.size() > 0) {
932 VLOG("Found periodic alarm fired.");
933 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
934 } else {
935 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
936 }
937 return Status::ok();
938}
939
Yao Chenef99c4f2017-09-22 16:26:54 -0700940Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600941 ENFORCE_UID(AID_SYSTEM);
942
yro74fed972017-11-27 14:42:42 -0800943 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700944 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -0800945 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700946 return Status::ok();
947}
948
Yao Chenef99c4f2017-09-22 16:26:54 -0700949Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600950 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700951
952 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800953 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -0700954 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700955 return Status::ok();
956}
957
Yangster-mac892f3d32018-05-02 14:16:48 -0700958Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600959 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -0700960 VLOG("StatsService::informDeviceShutdown");
Yangster-mac892f3d32018-05-02 14:16:48 -0700961 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN);
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800962 mProcessor->WriteMetricsActivationToDisk(getElapsedRealtimeNs());
yro947fbce2017-11-15 22:50:23 -0800963 return Status::ok();
964}
965
Yao Chenef99c4f2017-09-22 16:26:54 -0700966void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -0700967 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
968 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -0800969 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -0700970 statsCompanion->statsdReady();
971 } else {
yro74fed972017-11-27 14:42:42 -0800972 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -0700973 }
974}
975
Yao Chenef99c4f2017-09-22 16:26:54 -0700976Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600977 ENFORCE_UID(AID_SYSTEM);
978
yro74fed972017-11-27 14:42:42 -0800979 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -0700980 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
981 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700982 return Status::fromExceptionCode(
983 Status::EX_NULL_POINTER,
984 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700985 }
yro74fed972017-11-27 14:42:42 -0800986 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -0700987 IInterface::asBinder(statsCompanion)->linkToDeath(this);
Chenjie Yue2219202018-06-08 10:07:51 -0700988 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -0800989 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
990 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -0800991 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -0700992 return Status::ok();
993}
994
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700995void StatsService::Startup() {
996 mConfigManager->Startup();
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800997 mProcessor->LoadMetricsActivationFromDisk();
Bookatz906a35c2017-09-20 15:26:44 -0700998}
999
Yangster-mac97e7d202018-10-09 11:05:39 -07001000void StatsService::Terminate() {
1001 ALOGI("StatsService::Terminating");
1002 if (mProcessor != nullptr) {
1003 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED);
1004 }
1005}
1006
Yao Chen3ff3a492018-08-06 16:17:37 -07001007void StatsService::OnLogEvent(LogEvent* event) {
1008 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -07001009 if (mShellSubscriber != nullptr) {
1010 mShellSubscriber->onLogEvent(*event);
1011 }
Bookatz906a35c2017-09-20 15:26:44 -07001012}
1013
Jeff Sharkey6b649252018-04-16 09:50:22 -06001014Status StatsService::getData(int64_t key, const String16& packageName, vector<uint8_t>* output) {
1015 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1016
David Chenadaf8b32017-11-03 15:42:08 -07001017 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -08001018 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001019 ConfigKey configKey(ipc->getCallingUid(), key);
David Chen56ae0d92018-05-11 16:00:22 -07001020 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
Bookatzff71cad2018-09-20 17:17:49 -07001021 true /* erase_data */, GET_DATA_CALLED, output);
Bookatz4f716292018-04-10 17:15:12 -07001022 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001023}
1024
Jeff Sharkey6b649252018-04-16 09:50:22 -06001025Status StatsService::getMetadata(const String16& packageName, vector<uint8_t>* output) {
1026 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1027
David Chen2e8f3802017-11-22 10:56:48 -08001028 IPCThreadState* ipc = IPCThreadState::self();
1029 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
1030 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001031 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
1032 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -08001033}
1034
Jeff Sharkey6b649252018-04-16 09:50:22 -06001035Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
1036 const String16& packageName) {
1037 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1038
David Chenadaf8b32017-11-03 15:42:08 -07001039 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -07001040 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -08001041 return Status::ok();
1042 } else {
Bookatz4f716292018-04-10 17:15:12 -07001043 ALOGE("Could not parse malformatted StatsdConfig");
1044 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
1045 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -08001046 }
1047}
1048
David Chen9fdd4032018-03-20 14:38:56 -07001049bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
1050 ConfigKey configKey(uid, key);
1051 StatsdConfig cfg;
1052 if (config.size() > 0) { // If the config is empty, skip parsing.
1053 if (!cfg.ParseFromArray(&config[0], config.size())) {
1054 return false;
1055 }
1056 }
1057 mConfigManager->UpdateConfig(configKey, cfg);
1058 return true;
1059}
1060
Jeff Sharkey6b649252018-04-16 09:50:22 -06001061Status StatsService::removeDataFetchOperation(int64_t key, const String16& packageName) {
1062 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1063
Bookatz4f716292018-04-10 17:15:12 -07001064 IPCThreadState* ipc = IPCThreadState::self();
1065 ConfigKey configKey(ipc->getCallingUid(), key);
1066 mConfigManager->RemoveConfigReceiver(configKey);
1067 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -08001068}
1069
Jeff Sharkey6b649252018-04-16 09:50:22 -06001070Status StatsService::setDataFetchOperation(int64_t key,
1071 const sp<android::IBinder>& intentSender,
1072 const String16& packageName) {
1073 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1074
Bookatz4f716292018-04-10 17:15:12 -07001075 IPCThreadState* ipc = IPCThreadState::self();
1076 ConfigKey configKey(ipc->getCallingUid(), key);
1077 mConfigManager->SetConfigReceiver(configKey, intentSender);
David Chen48944902018-05-03 10:29:11 -07001078 if (StorageManager::hasConfigMetricsReport(configKey)) {
1079 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
1080 configKey.ToString().c_str());
1081 mProcessor->noteOnDiskData(configKey);
1082 }
Bookatz4f716292018-04-10 17:15:12 -07001083 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001084}
1085
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001086Status StatsService::setActiveConfigsChangedOperation(const sp<android::IBinder>& intentSender,
1087 const String16& packageName,
1088 vector<int64_t>* output) {
1089 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1090
1091 IPCThreadState* ipc = IPCThreadState::self();
Tej Singh6ede28b2019-01-29 17:06:54 -08001092 int uid = ipc->getCallingUid();
1093 mConfigManager->SetActiveConfigsChangedReceiver(uid, intentSender);
1094 if (output != nullptr) {
1095 mProcessor->GetActiveConfigs(uid, *output);
1096 } else {
1097 ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
1098 }
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001099 return Status::ok();
1100}
1101
1102Status StatsService::removeActiveConfigsChangedOperation(const String16& packageName) {
1103 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1104
1105 IPCThreadState* ipc = IPCThreadState::self();
1106 mConfigManager->RemoveActiveConfigsChangedReceiver(ipc->getCallingUid());
1107 return Status::ok();
1108}
1109
Jeff Sharkey6b649252018-04-16 09:50:22 -06001110Status StatsService::removeConfiguration(int64_t key, const String16& packageName) {
1111 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1112
Bookatz4f716292018-04-10 17:15:12 -07001113 IPCThreadState* ipc = IPCThreadState::self();
1114 ConfigKey configKey(ipc->getCallingUid(), key);
1115 mConfigManager->RemoveConfig(configKey);
1116 SubscriberReporter::getInstance().removeConfig(configKey);
1117 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001118}
1119
Bookatzc6977972018-01-16 16:55:05 -08001120Status StatsService::setBroadcastSubscriber(int64_t configId,
1121 int64_t subscriberId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001122 const sp<android::IBinder>& intentSender,
1123 const String16& packageName) {
1124 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1125
Bookatzc6977972018-01-16 16:55:05 -08001126 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001127 IPCThreadState* ipc = IPCThreadState::self();
1128 ConfigKey configKey(ipc->getCallingUid(), configId);
1129 SubscriberReporter::getInstance()
1130 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
1131 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001132}
1133
1134Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001135 int64_t subscriberId,
1136 const String16& packageName) {
1137 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1138
Bookatzc6977972018-01-16 16:55:05 -08001139 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001140 IPCThreadState* ipc = IPCThreadState::self();
1141 ConfigKey configKey(ipc->getCallingUid(), configId);
1142 SubscriberReporter::getInstance()
1143 .unsetBroadcastSubscriber(configKey, subscriberId);
1144 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001145}
1146
yrobe6d7f92018-05-04 13:02:53 -07001147Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
1148 // Permission check not necessary as it's meant for applications to write to
1149 // statsd.
1150 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
1151 IPCThreadState::self()->getCallingUid(), label,
1152 state);
1153 return Status::ok();
1154}
1155
Tej Singha0c89dd2019-01-25 16:39:18 -08001156Status StatsService::registerPullerCallback(int32_t atomTag,
1157 const sp<android::os::IStatsPullerCallback>& pullerCallback,
1158 const String16& packageName) {
1159 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1160
1161 VLOG("StatsService::registerPullerCallback called.");
1162 mPullerManager->RegisterPullerCallback(atomTag, pullerCallback);
1163 return Status::ok();
1164}
1165
1166Status StatsService::unregisterPullerCallback(int32_t atomTag, const String16& packageName) {
1167 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1168
1169 VLOG("StatsService::unregisterPullerCallback called.");
1170 mPullerManager->UnregisterPullerCallback(atomTag);
1171 return Status::ok();
1172}
1173
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001174Status StatsService::sendBinaryPushStateChangedAtom(const android::String16& trainName,
1175 int64_t trainVersionCode, int options,
1176 int32_t state,
1177 const std::vector<int64_t>& experimentIds) {
1178 uid_t uid = IPCThreadState::self()->getCallingUid();
1179 // For testing
1180 if (uid == AID_ROOT || uid == AID_SYSTEM || uid == AID_SHELL) {
1181 return ok();
1182 }
1183
1184 // Caller must be granted these permissions
1185 if (!checkCallingPermission(String16(kPermissionDump))) {
1186 return exception(binder::Status::EX_SECURITY,
1187 StringPrintf("UID %d lacks permission %s", uid, kPermissionDump));
1188 }
1189 if (!checkCallingPermission(String16(kPermissionUsage))) {
1190 return exception(binder::Status::EX_SECURITY,
1191 StringPrintf("UID %d lacks permission %s", uid, kPermissionUsage));
1192 }
1193 // TODO: add verifier permission
1194
1195 userid_t userId = multiuser_get_user_id(uid);
1196
1197 bool requiresStaging = options | IStatsManager::FLAG_REQUIRE_STAGING;
1198 bool rollbackEnabled = options | IStatsManager::FLAG_ROLLBACK_ENABLED;
1199 bool requiresLowLatencyMonitor = options | IStatsManager::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
1200
1201 ProtoOutputStream proto;
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001202 for (const auto& expId : experimentIds) {
1203 proto.write(FIELD_TYPE_INT64 | FIELD_COUNT_REPEATED | FIELD_ID_EXPERIMENT_ID,
1204 (long long)expId);
1205 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001206
1207 vector<uint8_t> buffer;
1208 buffer.resize(proto.size());
1209 size_t pos = 0;
1210 auto iter = proto.data();
1211 while (iter.readBuffer() != NULL) {
1212 size_t toRead = iter.currentToRead();
1213 std::memcpy(&(buffer[pos]), iter.readBuffer(), toRead);
1214 pos += toRead;
1215 iter.rp()->move(toRead);
1216 }
1217 LogEvent event(std::string(String8(trainName).string()), trainVersionCode, requiresStaging,
1218 rollbackEnabled, requiresLowLatencyMonitor, state, buffer, userId);
1219 mProcessor->OnLogEvent(&event);
1220 StorageManager::writeTrainInfo(trainVersionCode, buffer);
1221 return Status::ok();
1222}
1223
Howard Roa46b6582018-09-18 16:45:02 -07001224hardware::Return<void> StatsService::reportSpeakerImpedance(
1225 const SpeakerImpedance& speakerImpedance) {
1226 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), speakerImpedance);
1227 mProcessor->OnLogEvent(&event);
1228
1229 return hardware::Void();
1230}
1231
1232hardware::Return<void> StatsService::reportHardwareFailed(const HardwareFailed& hardwareFailed) {
1233 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), hardwareFailed);
1234 mProcessor->OnLogEvent(&event);
1235
1236 return hardware::Void();
1237}
1238
1239hardware::Return<void> StatsService::reportPhysicalDropDetected(
1240 const PhysicalDropDetected& physicalDropDetected) {
1241 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), physicalDropDetected);
1242 mProcessor->OnLogEvent(&event);
1243
1244 return hardware::Void();
1245}
1246
1247hardware::Return<void> StatsService::reportChargeCycles(const ChargeCycles& chargeCycles) {
1248 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), chargeCycles);
1249 mProcessor->OnLogEvent(&event);
1250
1251 return hardware::Void();
1252}
1253
1254hardware::Return<void> StatsService::reportBatteryHealthSnapshot(
1255 const BatteryHealthSnapshotArgs& batteryHealthSnapshotArgs) {
1256 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(),
1257 batteryHealthSnapshotArgs);
1258 mProcessor->OnLogEvent(&event);
1259
1260 return hardware::Void();
1261}
1262
1263hardware::Return<void> StatsService::reportSlowIo(const SlowIo& slowIo) {
1264 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), slowIo);
1265 mProcessor->OnLogEvent(&event);
1266
1267 return hardware::Void();
1268}
1269
1270hardware::Return<void> StatsService::reportBatteryCausedShutdown(
1271 const BatteryCausedShutdown& batteryCausedShutdown) {
1272 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), batteryCausedShutdown);
1273 mProcessor->OnLogEvent(&event);
1274
1275 return hardware::Void();
1276}
1277
Maggie Whitefc1aa592018-11-28 21:55:23 -08001278hardware::Return<void> StatsService::reportUsbPortOverheatEvent(
1279 const UsbPortOverheatEvent& usbPortOverheatEvent) {
1280 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), usbPortOverheatEvent);
1281 mProcessor->OnLogEvent(&event);
1282
1283 return hardware::Void();
1284}
1285
Carter Hsub8fd1e92019-01-11 15:24:45 +08001286hardware::Return<void> StatsService::reportSpeechDspStat(
1287 const SpeechDspStat& speechDspStat) {
1288 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), speechDspStat);
1289 mProcessor->OnLogEvent(&event);
1290
1291 return hardware::Void();
1292}
1293
Maggie White58174da2019-01-18 15:23:35 -08001294hardware::Return<void> StatsService::reportVendorAtom(const VendorAtom& vendorAtom) {
1295 std::string reverseDomainName = (std::string) vendorAtom.reverseDomainName;
1296 if (vendorAtom.atomId < 100000 || vendorAtom.atomId >= 200000) {
1297 ALOGE("Atom ID %ld is not a valid vendor atom ID", (long) vendorAtom.atomId);
1298 return hardware::Void();
1299 }
1300 if (reverseDomainName.length() > 50) {
1301 ALOGE("Vendor atom reverse domain name %s is too long.", reverseDomainName.c_str());
1302 return hardware::Void();
1303 }
1304 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), vendorAtom);
1305 mProcessor->OnLogEvent(&event);
1306
1307 return hardware::Void();
1308}
1309
David Chen1d7b0cd2017-11-15 14:20:04 -08001310void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001311 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001312 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1313 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001314 ALOGW("Reset statsd upon system server restarts.");
Yangster-mac892f3d32018-05-02 14:16:48 -07001315 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED);
1316 mProcessor->resetConfigs();
1317 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001318 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1319 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
1320 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001321 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001322}
1323
Yao Chenef99c4f2017-09-22 16:26:54 -07001324} // namespace statsd
1325} // namespace os
1326} // namespace android