blob: 8b5fca78afc86681c3fb6e6fc9e8ca08d97df188 [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
Chenjie Yu6b1667c2019-01-18 10:09:33 -080058const int FIELD_ID_EXPERIMENT_ID = 1;
59const int FIELD_ID_EXPERIMENT_ID_MSG = 7;
60
David Chenadaf8b32017-11-03 15:42:08 -070061constexpr const char* kPermissionDump = "android.permission.DUMP";
Jeff Sharkey6b649252018-04-16 09:50:22 -060062constexpr const char* kPermissionUsage = "android.permission.PACKAGE_USAGE_STATS";
63
64constexpr const char* kOpUsage = "android:get_usage_stats";
65
yro03faf092017-12-12 00:17:50 -080066#define STATS_SERVICE_DIR "/data/misc/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070067
Bookatzff71cad2018-09-20 17:17:49 -070068// for StatsDataDumpProto
69const int FIELD_ID_REPORTS_LIST = 1;
70
Jeff Sharkey6b649252018-04-16 09:50:22 -060071static binder::Status ok() {
72 return binder::Status::ok();
73}
74
75static binder::Status exception(uint32_t code, const std::string& msg) {
76 ALOGE("%s (%d)", msg.c_str(), code);
77 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
78}
79
80binder::Status checkUid(uid_t expectedUid) {
81 uid_t uid = IPCThreadState::self()->getCallingUid();
82 if (uid == expectedUid || uid == AID_ROOT) {
83 return ok();
84 } else {
85 return exception(binder::Status::EX_SECURITY,
86 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
87 }
88}
89
90binder::Status checkDumpAndUsageStats(const String16& packageName) {
91 pid_t pid = IPCThreadState::self()->getCallingPid();
92 uid_t uid = IPCThreadState::self()->getCallingUid();
93
94 // Root, system, and shell always have access
95 if (uid == AID_ROOT || uid == AID_SYSTEM || uid == AID_SHELL) {
96 return ok();
97 }
98
99 // Caller must be granted these permissions
100 if (!checkCallingPermission(String16(kPermissionDump))) {
101 return exception(binder::Status::EX_SECURITY,
102 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionDump));
103 }
104 if (!checkCallingPermission(String16(kPermissionUsage))) {
105 return exception(binder::Status::EX_SECURITY,
106 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionUsage));
107 }
108
109 // Caller must also have usage stats op granted
110 PermissionController pc;
111 switch (pc.noteOp(String16(kOpUsage), uid, packageName)) {
112 case PermissionController::MODE_ALLOWED:
113 case PermissionController::MODE_DEFAULT:
114 return ok();
115 default:
116 return exception(binder::Status::EX_SECURITY,
117 StringPrintf("UID %d / PID %d lacks app-op %s", uid, pid, kOpUsage));
118 }
119}
120
121#define ENFORCE_UID(uid) { \
122 binder::Status status = checkUid((uid)); \
123 if (!status.isOk()) { \
124 return status; \
125 } \
126}
127
128#define ENFORCE_DUMP_AND_USAGE_STATS(packageName) { \
129 binder::Status status = checkDumpAndUsageStats(packageName); \
130 if (!status.isOk()) { \
131 return status; \
132 } \
133}
134
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700135StatsService::StatsService(const sp<Looper>& handlerLooper)
Yangster-mac932ecec2018-02-01 10:23:52 -0800136 : mAnomalyAlarmMonitor(new AlarmMonitor(MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
137 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
138 if (sc != nullptr) {
139 sc->setAnomalyAlarm(timeMillis);
140 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
141 }
142 },
143 [](const sp<IStatsCompanionService>& sc) {
144 if (sc != nullptr) {
145 sc->cancelAnomalyAlarm();
146 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
147 }
148 })),
149 mPeriodicAlarmMonitor(new AlarmMonitor(MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
150 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
151 if (sc != nullptr) {
152 sc->setAlarmForSubscriberTriggering(timeMillis);
153 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
154 }
155 },
156 [](const sp<IStatsCompanionService>& sc) {
157 if (sc != nullptr) {
158 sc->cancelAlarmForSubscriberTriggering();
159 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
160 }
161
162 })) {
Yao Chen4ce07292019-02-13 13:06:36 -0800163 mUidMap = UidMap::getInstance();
Chenjie Yue2219202018-06-08 10:07:51 -0700164 mPullerManager = new StatsPullerManager();
Chenjie Yu80f91122018-01-31 20:24:50 -0800165 StatsPuller::SetUidMap(mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700166 mConfigManager = new ConfigManager();
Chenjie Yue2219202018-06-08 10:07:51 -0700167 mProcessor = new StatsLogProcessor(
168 mUidMap, mPullerManager, mAnomalyAlarmMonitor, mPeriodicAlarmMonitor,
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800169 getElapsedRealtimeNs(),
170 [this](const ConfigKey& key) {
Chenjie Yue2219202018-06-08 10:07:51 -0700171 sp<IStatsCompanionService> sc = getStatsCompanionService();
172 auto receiver = mConfigManager->GetConfigReceiver(key);
173 if (sc == nullptr) {
174 VLOG("Could not find StatsCompanionService");
175 return false;
176 } else if (receiver == nullptr) {
177 VLOG("Statscompanion could not find a broadcast receiver for %s",
178 key.ToString().c_str());
179 return false;
180 } else {
181 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
182 return true;
183 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800184 },
185 [this](const int& uid, const vector<int64_t>& activeConfigs) {
186 auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
187 sp<IStatsCompanionService> sc = getStatsCompanionService();
188 if (sc == nullptr) {
189 VLOG("Could not access statsCompanion");
190 return false;
191 } else if (receiver == nullptr) {
192 VLOG("Could not find receiver for uid %d", uid);
193 return false;
194 } else {
195 sc->sendActiveConfigsChangedBroadcast(receiver, activeConfigs);
196 VLOG("StatsService::active configs broadcast succeeded for uid %d" , uid);
197 return true;
198 }
Chenjie Yue2219202018-06-08 10:07:51 -0700199 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700200
201 mConfigManager->AddListener(mProcessor);
202
203 init_system_properties();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700204}
205
Yao Chenef99c4f2017-09-22 16:26:54 -0700206StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700207}
208
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700209void StatsService::init_system_properties() {
210 mEngBuild = false;
211 const prop_info* buildType = __system_property_find("ro.build.type");
212 if (buildType != NULL) {
213 __system_property_read_callback(buildType, init_build_type_callback, this);
214 }
David Chen0656b7a2017-09-13 15:53:39 -0700215}
216
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700217void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
218 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700219 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700220 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
221 }
222}
223
224/**
225 * Implement our own because the default binder implementation isn't
226 * properly handling SHELL_COMMAND_TRANSACTION.
227 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700228status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
229 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700230 switch (code) {
231 case SHELL_COMMAND_TRANSACTION: {
232 int in = data.readFileDescriptor();
233 int out = data.readFileDescriptor();
234 int err = data.readFileDescriptor();
235 int argc = data.readInt32();
236 Vector<String8> args;
237 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
238 args.add(String8(data.readString16()));
239 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700240 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
241 sp<IResultReceiver> resultReceiver =
242 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700243
Yao Chena80e5c02018-09-04 13:55:29 -0700244 err = command(in, out, err, args, resultReceiver);
245 resultReceiver->send(err);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700246 return NO_ERROR;
247 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700248 default: { return BnStatsManager::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700249 }
250}
251
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700252/**
Bookatzff71cad2018-09-20 17:17:49 -0700253 * Write data from statsd.
254 * Format for statsdStats: adb shell dumpsys stats --metadata [-v] [--proto]
255 * Format for data report: adb shell dumpsys stats [anything other than --metadata] [--proto]
256 * Anything ending in --proto will be in proto format.
257 * Anything without --metadata as the first argument will be report information.
258 * (bugreports call "adb shell dumpsys stats --dump-priority NORMAL -a --proto")
259 * TODO: Come up with a more robust method of enacting <serviceutils/PriorityDumper.h>.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700260 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700261status_t StatsService::dump(int fd, const Vector<String16>& args) {
Tej Singhdd83d702018-04-10 17:24:50 -0700262 if (!checkCallingPermission(String16(kPermissionDump))) {
263 return PERMISSION_DENIED;
264 }
Bookatzff71cad2018-09-20 17:17:49 -0700265 int lastArg = args.size() - 1;
266 bool asProto = false;
267 if (lastArg >= 0 && !args[lastArg].compare(String16("--proto"))) { // last argument
268 asProto = true;
269 lastArg--;
Yao Chen884c8c12018-01-26 10:36:25 -0800270 }
Bookatzff71cad2018-09-20 17:17:49 -0700271 if (args.size() > 0 && !args[0].compare(String16("--metadata"))) { // first argument
272 // Request is to dump statsd stats.
273 bool verbose = false;
274 if (lastArg >= 0 && !args[lastArg].compare(String16("-v"))) {
275 verbose = true;
276 lastArg--;
277 }
278 dumpStatsdStats(fd, verbose, asProto);
279 } else {
280 // Request is to dump statsd report data.
281 if (asProto) {
282 dumpIncidentSection(fd);
283 } else {
284 dprintf(fd, "Non-proto format of stats data dump not available; see proto version.\n");
285 }
Tej Singh41b3f9a2018-04-03 17:06:35 -0700286 }
Yao Chen884c8c12018-01-26 10:36:25 -0800287
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700288 return NO_ERROR;
289}
290
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700291/**
Tej Singh41b3f9a2018-04-03 17:06:35 -0700292 * Write debugging data about statsd in text or proto format.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700293 */
Bookatzff71cad2018-09-20 17:17:49 -0700294void StatsService::dumpStatsdStats(int out, bool verbose, bool proto) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700295 if (proto) {
296 vector<uint8_t> data;
297 StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
298 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700299 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700300 }
301 } else {
302 StatsdStats::getInstance().dumpStats(out);
303 mProcessor->dumpStates(out, verbose);
304 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700305}
306
307/**
Bookatzff71cad2018-09-20 17:17:49 -0700308 * Write stats report data in StatsDataDumpProto incident section format.
309 */
310void StatsService::dumpIncidentSection(int out) {
311 ProtoOutputStream proto;
312 for (const ConfigKey& configKey : mConfigManager->GetAllConfigKeys()) {
313 uint64_t reportsListToken =
314 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS_LIST);
315 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
316 true /* includeCurrentBucket */, false /* erase_data */,
317 ADB_DUMP, &proto);
318 proto.end(reportsListToken);
319 proto.flush(out);
Bookatzc71d9012018-12-19 12:28:38 -0800320 proto.clear();
Bookatzff71cad2018-09-20 17:17:49 -0700321 }
322}
323
324/**
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700325 * Implementation of the adb shell cmd stats command.
326 */
Yao Chena80e5c02018-09-04 13:55:29 -0700327status_t StatsService::command(int in, int out, int err, Vector<String8>& args,
328 sp<IResultReceiver> resultReceiver) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600329 uid_t uid = IPCThreadState::self()->getCallingUid();
330 if (uid != AID_ROOT && uid != AID_SHELL) {
331 return PERMISSION_DENIED;
332 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700333
334 const int argCount = args.size();
335 if (argCount >= 1) {
336 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700337 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700338 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700339 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700340
David Chende701692017-10-05 13:16:02 -0700341 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800342 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700343 }
Yao Chen729093d2017-10-16 10:33:26 -0700344
345 if (!args[0].compare(String8("dump-report"))) {
Bookatzff71cad2018-09-20 17:17:49 -0700346 return cmd_dump_report(out, args);
Yao Chen729093d2017-10-16 10:33:26 -0700347 }
David Chen1481fe12017-10-16 13:16:34 -0700348
349 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
350 return cmd_print_pulled_metrics(out, args);
351 }
David Chenadaf8b32017-11-03 15:42:08 -0700352
353 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800354 return cmd_trigger_broadcast(out, args);
355 }
356
357 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800358 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700359 }
yro87d983c2017-11-14 21:31:43 -0800360
Yao Chen8d9989b2017-11-18 18:54:50 -0800361 if (!args[0].compare(String8("meminfo"))) {
362 return cmd_dump_memory_info(out);
363 }
yro947fbce2017-11-15 22:50:23 -0800364
365 if (!args[0].compare(String8("write-to-disk"))) {
366 return cmd_write_data_to_disk(out);
367 }
Bookatzb223c4e2018-02-01 15:35:04 -0800368
David Chen0b5c90c2018-01-25 16:51:49 -0800369 if (!args[0].compare(String8("log-app-breadcrumb"))) {
370 return cmd_log_app_breadcrumb(out, args);
Bookatzb223c4e2018-02-01 15:35:04 -0800371 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800372
373 if (!args[0].compare(String8("clear-puller-cache"))) {
374 return cmd_clear_puller_cache(out);
375 }
Yao Chen876889c2018-05-02 11:16:16 -0700376
377 if (!args[0].compare(String8("print-logs"))) {
378 return cmd_print_logs(out, args);
379 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800380 if (!args[0].compare(String8("send-active-configs"))) {
381 return cmd_trigger_active_config_broadcast(out, args);
382 }
Yao Chena80e5c02018-09-04 13:55:29 -0700383 if (!args[0].compare(String8("data-subscribe"))) {
384 if (mShellSubscriber == nullptr) {
Yao Chen41e606c2018-10-05 15:54:11 -0700385 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
Yao Chena80e5c02018-09-04 13:55:29 -0700386 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800387 int timeoutSec = -1;
388 if (argCount >= 2) {
389 timeoutSec = atoi(args[1].c_str());
390 }
391 mShellSubscriber->startNewSubscription(in, out, resultReceiver, timeoutSec);
Yao Chena80e5c02018-09-04 13:55:29 -0700392 return NO_ERROR;
393 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700394 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700395
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700396 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700397 return NO_ERROR;
398}
399
Yao Chena80e5c02018-09-04 13:55:29 -0700400void StatsService::print_cmd_help(int out) {
401 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700402 "usage: adb shell cmd stats print-stats-log [tag_required] "
403 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700404 dprintf(out, "\n");
405 dprintf(out, "\n");
406 dprintf(out, "usage: adb shell cmd stats meminfo\n");
407 dprintf(out, "\n");
408 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
409 dprintf(out, " # adb shell stop\n");
410 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
411 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
412 dprintf(out, " # adb shell start\n");
413 dprintf(out, "\n");
414 dprintf(out, "\n");
415 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
416 dprintf(out, "\n");
417 dprintf(out, " Prints the UID, app name, version mapping.\n");
418 dprintf(out, " PKG Optional package name to print the uids of the package\n");
419 dprintf(out, "\n");
420 dprintf(out, "\n");
421 dprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
422 dprintf(out, "\n");
423 dprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
424 dprintf(out, "\n");
425 dprintf(out, "\n");
426 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
427 dprintf(out, "\n");
428 dprintf(out, " Flushes all data on memory to disk.\n");
429 dprintf(out, "\n");
430 dprintf(out, "\n");
431 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
432 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
433 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
434 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
435 dprintf(out, " uid is used.\n");
436 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
437 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
438 dprintf(out, "\n");
439 dprintf(out, "\n");
440 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
441 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
442 dprintf(out, "\n");
443 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
444 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
445 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
446 dprintf(out, "\n");
447 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
448 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
449 dprintf(out, " uid is used.\n");
450 dprintf(out, " NAME The per-uid name to use\n");
451 dprintf(out, "\n");
452 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
453 dprintf(out, "\n be removed from memory and disk!\n");
454 dprintf(out, "\n");
455 dprintf(out,
Bookatz3e906582018-12-10 17:26:58 -0800456 "usage: adb shell cmd stats dump-report [UID] NAME [--keep_data] "
457 "[--include_current_bucket] [--proto]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700458 dprintf(out, " Dump all metric data for a configuration.\n");
459 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
460 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
461 dprintf(out, " calling uid is used.\n");
462 dprintf(out, " NAME The name of the configuration\n");
Bookatz3e906582018-12-10 17:26:58 -0800463 dprintf(out, " --keep_data Do NOT erase the data upon dumping it.\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700464 dprintf(out, " --proto Print proto binary.\n");
465 dprintf(out, "\n");
466 dprintf(out, "\n");
467 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
468 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
469 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
470 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
471 dprintf(out, " calling uid is used.\n");
472 dprintf(out, " NAME The name of the configuration\n");
473 dprintf(out, "\n");
474 dprintf(out, "\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800475 dprintf(out,
476 "usage: adb shell cmd stats send-active-configs [--uid=UID] [--configs] "
477 "[NAME1] [NAME2] [NAME3..]\n");
478 dprintf(out, " Send a broadcast that informs the subscriber of the current active configs.\n");
479 dprintf(out, " --uid=UID The uid of the configurations. It is only possible to pass\n");
480 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
481 dprintf(out, " calling uid is used.\n");
482 dprintf(out, " --configs Send the list of configs in the name list instead of\n");
483 dprintf(out, " the currently active configs\n");
484 dprintf(out, " NAME LIST List of configuration names to be included in the broadcast.\n");
485
486 dprintf(out, "\n");
487 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700488 dprintf(out, "usage: adb shell cmd stats print-stats\n");
489 dprintf(out, " Prints some basic stats.\n");
490 dprintf(out, " --proto Print proto binary instead of string format.\n");
491 dprintf(out, "\n");
492 dprintf(out, "\n");
493 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
494 dprintf(out, " Clear cached puller data.\n");
495 dprintf(out, "\n");
496 dprintf(out, "usage: adb shell cmd stats print-logs\n");
497 dprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700498}
499
Yao Chena80e5c02018-09-04 13:55:29 -0700500status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800501 string name;
502 bool good = false;
503 int uid;
504 const int argCount = args.size();
505 if (argCount == 2) {
506 // Automatically pick the UID
507 uid = IPCThreadState::self()->getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800508 name.assign(args[1].c_str(), args[1].size());
509 good = true;
510 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800511 good = getUidFromArgs(args, 1, uid);
512 if (!good) {
513 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
514 "other UIDs on eng or userdebug builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800515 }
Bookatzd2386572018-12-14 15:53:14 -0800516 name.assign(args[2].c_str(), args[2].size());
David Chen1d7b0cd2017-11-15 14:20:04 -0800517 }
518 if (!good) {
519 print_cmd_help(out);
520 return UNKNOWN_ERROR;
521 }
David Chend37bc232018-04-12 18:05:11 -0700522 ConfigKey key(uid, StrToInt64(name));
523 auto receiver = mConfigManager->GetConfigReceiver(key);
yro4d889e62017-11-17 15:44:48 -0800524 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen661f7912018-01-22 17:46:24 -0800525 if (sc == nullptr) {
526 VLOG("Could not access statsCompanion");
527 } else if (receiver == nullptr) {
528 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str())
529 } else {
David Chend37bc232018-04-12 18:05:11 -0700530 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
yro74fed972017-11-27 14:42:42 -0800531 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
532 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800533 }
534
David Chenadaf8b32017-11-03 15:42:08 -0700535 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700536}
537
Tej Singh6ede28b2019-01-29 17:06:54 -0800538status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
539 const int argCount = args.size();
540 int uid;
541 vector<int64_t> configIds;
542 if (argCount == 1) {
543 // Automatically pick the uid and send a broadcast that has no active configs.
544 uid = IPCThreadState::self()->getCallingUid();
545 mProcessor->GetActiveConfigs(uid, configIds);
546 } else {
547 int curArg = 1;
548 if(args[curArg].find("--uid=") == 0) {
549 string uidArgStr(args[curArg].c_str());
550 string uidStr = uidArgStr.substr(6);
551 if (!getUidFromString(uidStr.c_str(), uid)) {
552 dprintf(out, "Invalid UID. Note that the config can only be set for "
553 "other UIDs on eng or userdebug builds.\n");
554 return UNKNOWN_ERROR;
555 }
556 curArg++;
557 } else {
558 uid = IPCThreadState::self()->getCallingUid();
559 }
560 if (curArg == argCount || args[curArg] != "--configs") {
561 VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
562 mProcessor->GetActiveConfigs(uid, configIds);
563 } else {
564 // Flag specified, use the given list of configs.
565 curArg++;
566 for (int i = curArg; i < argCount; i++) {
567 char* endp;
568 int64_t configID = strtoll(args[i].c_str(), &endp, 10);
569 if (endp == args[i].c_str() || *endp != '\0') {
570 dprintf(out, "Error parsing config ID.\n");
571 return UNKNOWN_ERROR;
572 }
573 VLOG("Adding config id %ld", static_cast<long>(configID));
574 configIds.push_back(configID);
575 }
576 }
577 }
578 auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
579 sp<IStatsCompanionService> sc = getStatsCompanionService();
580 if (sc == nullptr) {
581 VLOG("Could not access statsCompanion");
582 } else if (receiver == nullptr) {
583 VLOG("Could not find receiver for uid %d", uid);
584 } else {
585 sc->sendActiveConfigsChangedBroadcast(receiver, configIds);
586 VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
587 }
588 return NO_ERROR;
589}
590
Yao Chena80e5c02018-09-04 13:55:29 -0700591status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700592 const int argCount = args.size();
593 if (argCount >= 2) {
594 if (args[1] == "update" || args[1] == "remove") {
595 bool good = false;
596 int uid = -1;
597 string name;
598
599 if (argCount == 3) {
600 // Automatically pick the UID
601 uid = IPCThreadState::self()->getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700602 name.assign(args[2].c_str(), args[2].size());
603 good = true;
604 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800605 good = getUidFromArgs(args, 2, uid);
606 if (!good) {
607 dprintf(err, "Invalid UID. Note that the config can only be set for "
608 "other UIDs on eng or userdebug builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700609 }
Bookatzd2386572018-12-14 15:53:14 -0800610 name.assign(args[3].c_str(), args[3].size());
yroe5f82922018-01-22 18:37:27 -0800611 } else if (argCount == 2 && args[1] == "remove") {
612 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700613 }
614
615 if (!good) {
616 // If arg parsing failed, print the help text and return an error.
617 print_cmd_help(out);
618 return UNKNOWN_ERROR;
619 }
620
621 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800622 char* endp;
623 int64_t configID = strtoll(name.c_str(), &endp, 10);
624 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700625 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800626 return UNKNOWN_ERROR;
627 }
628
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700629 // Read stream into buffer.
630 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700631 if (!android::base::ReadFdToString(in, &buffer)) {
632 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700633 return UNKNOWN_ERROR;
634 }
635
636 // Parse buffer.
637 StatsdConfig config;
638 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700639 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700640 return UNKNOWN_ERROR;
641 }
642
643 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800644 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700645 } else {
yro74fed972017-11-27 14:42:42 -0800646 if (argCount == 2) {
647 cmd_remove_all_configs(out);
648 } else {
649 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800650 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800651 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700652 }
653
654 return NO_ERROR;
655 }
David Chen0656b7a2017-09-13 15:53:39 -0700656 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700657 print_cmd_help(out);
658 return UNKNOWN_ERROR;
659}
660
Bookatzff71cad2018-09-20 17:17:49 -0700661status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700662 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800663 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700664 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800665 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700666 bool includeCurrentBucket = false;
Bookatz3e906582018-12-10 17:26:58 -0800667 bool eraseData = true;
Yao Chen729093d2017-10-16 10:33:26 -0700668 int uid;
669 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800670 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
671 proto = true;
672 argCount -= 1;
673 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700674 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
675 includeCurrentBucket = true;
676 argCount -= 1;
677 }
Bookatz3e906582018-12-10 17:26:58 -0800678 if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
679 eraseData = false;
680 argCount -= 1;
681 }
Yao Chen729093d2017-10-16 10:33:26 -0700682 if (argCount == 2) {
683 // Automatically pick the UID
684 uid = IPCThreadState::self()->getCallingUid();
Yao Chen5154a372017-10-30 22:57:06 -0700685 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700686 good = true;
687 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800688 good = getUidFromArgs(args, 1, uid);
689 if (!good) {
690 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
691 "other UIDs on eng or userdebug builds.\n");
Yao Chen729093d2017-10-16 10:33:26 -0700692 }
Bookatzd2386572018-12-14 15:53:14 -0800693 name.assign(args[2].c_str(), args[2].size());
Yao Chen729093d2017-10-16 10:33:26 -0700694 }
695 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800696 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800697 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Bookatz3e906582018-12-10 17:26:58 -0800698 includeCurrentBucket, eraseData, ADB_DUMP, &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800699 if (proto) {
700 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700701 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800702 }
703 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700704 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800705 }
Yao Chen729093d2017-10-16 10:33:26 -0700706 return android::OK;
707 } else {
708 // If arg parsing failed, print the help text and return an error.
709 print_cmd_help(out);
710 return UNKNOWN_ERROR;
711 }
712 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700713 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700714 return UNKNOWN_ERROR;
715 }
716}
717
Yao Chena80e5c02018-09-04 13:55:29 -0700718status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700719 int argCount = args.size();
720 bool proto = false;
721 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
722 proto = true;
723 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800724 }
Yao Chenb3561512017-11-21 18:07:17 -0800725 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700726 if (proto) {
727 vector<uint8_t> data;
728 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
729 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700730 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700731 }
732
733 } else {
734 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
735 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700736 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700737 mProcessor->GetMetricsSize(key));
738 }
739 statsdStats.dumpStats(out);
740 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800741 return NO_ERROR;
742}
743
Yao Chena80e5c02018-09-04 13:55:29 -0700744status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800745 if (args.size() > 1) {
746 string pkg;
747 pkg.assign(args[1].c_str(), args[1].size());
748 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700749 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800750 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700751 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800752 }
Yao Chena80e5c02018-09-04 13:55:29 -0700753 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800754 } else {
755 mUidMap->printUidMap(out);
756 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700757 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700758}
759
Yao Chena80e5c02018-09-04 13:55:29 -0700760status_t StatsService::cmd_write_data_to_disk(int out) {
761 dprintf(out, "Writing data to disk\n");
Yangster-mac892f3d32018-05-02 14:16:48 -0700762 mProcessor->WriteDataToDisk(ADB_DUMP);
yro947fbce2017-11-15 22:50:23 -0800763 return NO_ERROR;
764}
765
Yao Chena80e5c02018-09-04 13:55:29 -0700766status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800767 bool good = false;
768 int32_t uid;
769 int32_t label;
770 int32_t state;
771 const int argCount = args.size();
772 if (argCount == 3) {
773 // Automatically pick the UID
774 uid = IPCThreadState::self()->getCallingUid();
775 label = atoi(args[1].c_str());
776 state = atoi(args[2].c_str());
777 good = true;
778 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800779 good = getUidFromArgs(args, 1, uid);
780 if (!good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700781 dprintf(out,
Bookatzd2386572018-12-14 15:53:14 -0800782 "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
783 "done for other UIDs on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800784 }
Bookatzd2386572018-12-14 15:53:14 -0800785 label = atoi(args[2].c_str());
786 state = atoi(args[3].c_str());
Bookatzb223c4e2018-02-01 15:35:04 -0800787 }
788 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700789 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
David Chen0b5c90c2018-01-25 16:51:49 -0800790 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800791 } else {
792 print_cmd_help(out);
793 return UNKNOWN_ERROR;
794 }
795 return NO_ERROR;
796}
797
Yao Chena80e5c02018-09-04 13:55:29 -0700798status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700799 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700800 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800801 if (mPullerManager->Pull(s, &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700802 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700803 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700804 }
Yao Chena80e5c02018-09-04 13:55:29 -0700805 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700806 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700807 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700808 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700809}
810
Yao Chena80e5c02018-09-04 13:55:29 -0700811status_t StatsService::cmd_remove_all_configs(int out) {
812 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800813 VLOG("StatsService::cmd_remove_all_configs was called");
814 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800815 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800816 return NO_ERROR;
817}
818
Yao Chena80e5c02018-09-04 13:55:29 -0700819status_t StatsService::cmd_dump_memory_info(int out) {
820 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800821 return NO_ERROR;
822}
823
Yao Chena80e5c02018-09-04 13:55:29 -0700824status_t StatsService::cmd_clear_puller_cache(int out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800825 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800826 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
827 ipc->getCallingPid(), ipc->getCallingUid());
Chenjie Yufa22d652018-02-05 14:37:48 -0800828 if (checkCallingPermission(String16(kPermissionDump))) {
Chenjie Yue2219202018-06-08 10:07:51 -0700829 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700830 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800831 return NO_ERROR;
832 } else {
833 return PERMISSION_DENIED;
834 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800835}
836
Yao Chena80e5c02018-09-04 13:55:29 -0700837status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Yao Chen876889c2018-05-02 11:16:16 -0700838 IPCThreadState* ipc = IPCThreadState::self();
839 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", ipc->getCallingPid(),
840 ipc->getCallingUid());
841 if (checkCallingPermission(String16(kPermissionDump))) {
842 bool enabled = true;
843 if (args.size() >= 2) {
844 enabled = atoi(args[1].c_str()) != 0;
845 }
846 mProcessor->setPrintLogs(enabled);
847 return NO_ERROR;
848 } else {
849 return PERMISSION_DENIED;
850 }
851}
852
Bookatzd2386572018-12-14 15:53:14 -0800853bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800854 return getUidFromString(args[uidArgIndex].c_str(), uid);
855}
856
857bool StatsService::getUidFromString(const char* s, int32_t& uid) {
Bookatzd2386572018-12-14 15:53:14 -0800858 if (*s == '\0') {
859 return false;
860 }
861 char* endc = NULL;
862 int64_t longUid = strtol(s, &endc, 0);
863 if (*endc != '\0') {
864 return false;
865 }
866 int32_t goodUid = static_cast<int32_t>(longUid);
867 if (longUid < 0 || static_cast<uint64_t>(longUid) != static_cast<uid_t>(goodUid)) {
868 return false; // It was not of uid_t type.
869 }
870 uid = goodUid;
871
872 int32_t callingUid = IPCThreadState::self()->getCallingUid();
873 return mEngBuild // UserDebug/EngBuild are allowed to impersonate uids.
874 || (callingUid == goodUid) // Anyone can 'impersonate' themselves.
875 || (callingUid == AID_ROOT && goodUid == AID_SHELL); // ROOT can impersonate SHELL.
876}
877
Dianne Hackborn3accca02013-09-20 09:32:11 -0700878Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int64_t>& version,
dwchen730403e2018-10-29 11:41:56 -0700879 const vector<String16>& version_string,
880 const vector<String16>& app,
881 const vector<String16>& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600882 ENFORCE_UID(AID_SYSTEM);
883
yro74fed972017-11-27 14:42:42 -0800884 VLOG("StatsService::informAllUidData was called");
dwchen730403e2018-10-29 11:41:56 -0700885 mUidMap->updateMap(getElapsedRealtimeNs(), uid, version, version_string, app, installer);
yro74fed972017-11-27 14:42:42 -0800886 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700887
888 return Status::ok();
889}
890
dwchen730403e2018-10-29 11:41:56 -0700891Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version,
892 const String16& version_string, const String16& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600893 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700894
Jeff Sharkey6b649252018-04-16 09:50:22 -0600895 VLOG("StatsService::informOnePackage was called");
dwchen730403e2018-10-29 11:41:56 -0700896 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version, version_string, installer);
David Chende701692017-10-05 13:16:02 -0700897 return Status::ok();
898}
899
900Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600901 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700902
Jeff Sharkey6b649252018-04-16 09:50:22 -0600903 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -0700904 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -0800905 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -0700906 return Status::ok();
907}
908
Yao Chenef99c4f2017-09-22 16:26:54 -0700909Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600910 ENFORCE_UID(AID_SYSTEM);
911
yro74fed972017-11-27 14:42:42 -0800912 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700913 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800914 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
915 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
916 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -0800917 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -0800918 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -0800919 } else {
920 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
921 }
Bookatz1b0b1142017-09-08 11:58:42 -0700922 return Status::ok();
923}
924
Yangster-mac932ecec2018-02-01 10:23:52 -0800925Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600926 ENFORCE_UID(AID_SYSTEM);
927
Yangster-mac932ecec2018-02-01 10:23:52 -0800928 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700929 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800930 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
931 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
932 if (alarmSet.size() > 0) {
933 VLOG("Found periodic alarm fired.");
934 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
935 } else {
936 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
937 }
938 return Status::ok();
939}
940
Yao Chenef99c4f2017-09-22 16:26:54 -0700941Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600942 ENFORCE_UID(AID_SYSTEM);
943
yro74fed972017-11-27 14:42:42 -0800944 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -0700945 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -0800946 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -0700947 return Status::ok();
948}
949
Yao Chenef99c4f2017-09-22 16:26:54 -0700950Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600951 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700952
953 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -0800954 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -0700955 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700956 return Status::ok();
957}
958
Yangster-mac892f3d32018-05-02 14:16:48 -0700959Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600960 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -0700961 VLOG("StatsService::informDeviceShutdown");
Yangster-mac892f3d32018-05-02 14:16:48 -0700962 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN);
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800963 mProcessor->WriteMetricsActivationToDisk(getElapsedRealtimeNs());
yro947fbce2017-11-15 22:50:23 -0800964 return Status::ok();
965}
966
Yao Chenef99c4f2017-09-22 16:26:54 -0700967void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -0700968 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
969 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -0800970 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -0700971 statsCompanion->statsdReady();
972 } else {
yro74fed972017-11-27 14:42:42 -0800973 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -0700974 }
975}
976
Yao Chenef99c4f2017-09-22 16:26:54 -0700977Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600978 ENFORCE_UID(AID_SYSTEM);
979
yro74fed972017-11-27 14:42:42 -0800980 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -0700981 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
982 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -0700983 return Status::fromExceptionCode(
984 Status::EX_NULL_POINTER,
985 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -0700986 }
yro74fed972017-11-27 14:42:42 -0800987 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -0700988 IInterface::asBinder(statsCompanion)->linkToDeath(this);
Chenjie Yue2219202018-06-08 10:07:51 -0700989 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -0800990 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
991 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -0800992 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -0700993 return Status::ok();
994}
995
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700996void StatsService::Startup() {
997 mConfigManager->Startup();
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800998 mProcessor->LoadMetricsActivationFromDisk();
Bookatz906a35c2017-09-20 15:26:44 -0700999}
1000
Yangster-mac97e7d202018-10-09 11:05:39 -07001001void StatsService::Terminate() {
1002 ALOGI("StatsService::Terminating");
1003 if (mProcessor != nullptr) {
1004 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED);
1005 }
1006}
1007
Yao Chen3ff3a492018-08-06 16:17:37 -07001008void StatsService::OnLogEvent(LogEvent* event) {
1009 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -07001010 if (mShellSubscriber != nullptr) {
1011 mShellSubscriber->onLogEvent(*event);
1012 }
Bookatz906a35c2017-09-20 15:26:44 -07001013}
1014
Jeff Sharkey6b649252018-04-16 09:50:22 -06001015Status StatsService::getData(int64_t key, const String16& packageName, vector<uint8_t>* output) {
1016 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1017
David Chenadaf8b32017-11-03 15:42:08 -07001018 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -08001019 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001020 ConfigKey configKey(ipc->getCallingUid(), key);
David Chen56ae0d92018-05-11 16:00:22 -07001021 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
Bookatzff71cad2018-09-20 17:17:49 -07001022 true /* erase_data */, GET_DATA_CALLED, output);
Bookatz4f716292018-04-10 17:15:12 -07001023 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001024}
1025
Jeff Sharkey6b649252018-04-16 09:50:22 -06001026Status StatsService::getMetadata(const String16& packageName, vector<uint8_t>* output) {
1027 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1028
David Chen2e8f3802017-11-22 10:56:48 -08001029 IPCThreadState* ipc = IPCThreadState::self();
1030 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
1031 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001032 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
1033 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -08001034}
1035
Jeff Sharkey6b649252018-04-16 09:50:22 -06001036Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
1037 const String16& packageName) {
1038 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1039
David Chenadaf8b32017-11-03 15:42:08 -07001040 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -07001041 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -08001042 return Status::ok();
1043 } else {
Bookatz4f716292018-04-10 17:15:12 -07001044 ALOGE("Could not parse malformatted StatsdConfig");
1045 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
1046 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -08001047 }
1048}
1049
David Chen9fdd4032018-03-20 14:38:56 -07001050bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
1051 ConfigKey configKey(uid, key);
1052 StatsdConfig cfg;
1053 if (config.size() > 0) { // If the config is empty, skip parsing.
1054 if (!cfg.ParseFromArray(&config[0], config.size())) {
1055 return false;
1056 }
1057 }
1058 mConfigManager->UpdateConfig(configKey, cfg);
1059 return true;
1060}
1061
Jeff Sharkey6b649252018-04-16 09:50:22 -06001062Status StatsService::removeDataFetchOperation(int64_t key, const String16& packageName) {
1063 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1064
Bookatz4f716292018-04-10 17:15:12 -07001065 IPCThreadState* ipc = IPCThreadState::self();
1066 ConfigKey configKey(ipc->getCallingUid(), key);
1067 mConfigManager->RemoveConfigReceiver(configKey);
1068 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -08001069}
1070
Jeff Sharkey6b649252018-04-16 09:50:22 -06001071Status StatsService::setDataFetchOperation(int64_t key,
1072 const sp<android::IBinder>& intentSender,
1073 const String16& packageName) {
1074 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1075
Bookatz4f716292018-04-10 17:15:12 -07001076 IPCThreadState* ipc = IPCThreadState::self();
1077 ConfigKey configKey(ipc->getCallingUid(), key);
1078 mConfigManager->SetConfigReceiver(configKey, intentSender);
David Chen48944902018-05-03 10:29:11 -07001079 if (StorageManager::hasConfigMetricsReport(configKey)) {
1080 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
1081 configKey.ToString().c_str());
1082 mProcessor->noteOnDiskData(configKey);
1083 }
Bookatz4f716292018-04-10 17:15:12 -07001084 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001085}
1086
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001087Status StatsService::setActiveConfigsChangedOperation(const sp<android::IBinder>& intentSender,
1088 const String16& packageName,
1089 vector<int64_t>* output) {
1090 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1091
1092 IPCThreadState* ipc = IPCThreadState::self();
Tej Singh6ede28b2019-01-29 17:06:54 -08001093 int uid = ipc->getCallingUid();
1094 mConfigManager->SetActiveConfigsChangedReceiver(uid, intentSender);
1095 if (output != nullptr) {
1096 mProcessor->GetActiveConfigs(uid, *output);
1097 } else {
1098 ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
1099 }
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001100 return Status::ok();
1101}
1102
1103Status StatsService::removeActiveConfigsChangedOperation(const String16& packageName) {
1104 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1105
1106 IPCThreadState* ipc = IPCThreadState::self();
1107 mConfigManager->RemoveActiveConfigsChangedReceiver(ipc->getCallingUid());
1108 return Status::ok();
1109}
1110
Jeff Sharkey6b649252018-04-16 09:50:22 -06001111Status StatsService::removeConfiguration(int64_t key, const String16& packageName) {
1112 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1113
Bookatz4f716292018-04-10 17:15:12 -07001114 IPCThreadState* ipc = IPCThreadState::self();
1115 ConfigKey configKey(ipc->getCallingUid(), key);
1116 mConfigManager->RemoveConfig(configKey);
1117 SubscriberReporter::getInstance().removeConfig(configKey);
1118 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001119}
1120
Bookatzc6977972018-01-16 16:55:05 -08001121Status StatsService::setBroadcastSubscriber(int64_t configId,
1122 int64_t subscriberId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001123 const sp<android::IBinder>& intentSender,
1124 const String16& packageName) {
1125 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1126
Bookatzc6977972018-01-16 16:55:05 -08001127 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001128 IPCThreadState* ipc = IPCThreadState::self();
1129 ConfigKey configKey(ipc->getCallingUid(), configId);
1130 SubscriberReporter::getInstance()
1131 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
1132 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001133}
1134
1135Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001136 int64_t subscriberId,
1137 const String16& packageName) {
1138 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1139
Bookatzc6977972018-01-16 16:55:05 -08001140 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001141 IPCThreadState* ipc = IPCThreadState::self();
1142 ConfigKey configKey(ipc->getCallingUid(), configId);
1143 SubscriberReporter::getInstance()
1144 .unsetBroadcastSubscriber(configKey, subscriberId);
1145 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001146}
1147
yrobe6d7f92018-05-04 13:02:53 -07001148Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
1149 // Permission check not necessary as it's meant for applications to write to
1150 // statsd.
1151 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
1152 IPCThreadState::self()->getCallingUid(), label,
1153 state);
1154 return Status::ok();
1155}
1156
Tej Singha0c89dd2019-01-25 16:39:18 -08001157Status StatsService::registerPullerCallback(int32_t atomTag,
1158 const sp<android::os::IStatsPullerCallback>& pullerCallback,
1159 const String16& packageName) {
1160 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1161
1162 VLOG("StatsService::registerPullerCallback called.");
1163 mPullerManager->RegisterPullerCallback(atomTag, pullerCallback);
1164 return Status::ok();
1165}
1166
1167Status StatsService::unregisterPullerCallback(int32_t atomTag, const String16& packageName) {
1168 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1169
1170 VLOG("StatsService::unregisterPullerCallback called.");
1171 mPullerManager->UnregisterPullerCallback(atomTag);
1172 return Status::ok();
1173}
1174
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001175Status StatsService::sendBinaryPushStateChangedAtom(const android::String16& trainName,
1176 int64_t trainVersionCode, int options,
1177 int32_t state,
1178 const std::vector<int64_t>& experimentIds) {
1179 uid_t uid = IPCThreadState::self()->getCallingUid();
1180 // For testing
1181 if (uid == AID_ROOT || uid == AID_SYSTEM || uid == AID_SHELL) {
1182 return ok();
1183 }
1184
1185 // Caller must be granted these permissions
1186 if (!checkCallingPermission(String16(kPermissionDump))) {
1187 return exception(binder::Status::EX_SECURITY,
1188 StringPrintf("UID %d lacks permission %s", uid, kPermissionDump));
1189 }
1190 if (!checkCallingPermission(String16(kPermissionUsage))) {
1191 return exception(binder::Status::EX_SECURITY,
1192 StringPrintf("UID %d lacks permission %s", uid, kPermissionUsage));
1193 }
1194 // TODO: add verifier permission
1195
1196 userid_t userId = multiuser_get_user_id(uid);
1197
1198 bool requiresStaging = options | IStatsManager::FLAG_REQUIRE_STAGING;
1199 bool rollbackEnabled = options | IStatsManager::FLAG_ROLLBACK_ENABLED;
1200 bool requiresLowLatencyMonitor = options | IStatsManager::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
1201
1202 ProtoOutputStream proto;
1203 uint64_t protoToken = proto.start(FIELD_TYPE_MESSAGE | FIELD_ID_EXPERIMENT_ID_MSG);
1204 for (const auto& expId : experimentIds) {
1205 proto.write(FIELD_TYPE_INT64 | FIELD_COUNT_REPEATED | FIELD_ID_EXPERIMENT_ID,
1206 (long long)expId);
1207 }
1208 proto.end(protoToken);
1209
1210 vector<uint8_t> buffer;
1211 buffer.resize(proto.size());
1212 size_t pos = 0;
1213 auto iter = proto.data();
1214 while (iter.readBuffer() != NULL) {
1215 size_t toRead = iter.currentToRead();
1216 std::memcpy(&(buffer[pos]), iter.readBuffer(), toRead);
1217 pos += toRead;
1218 iter.rp()->move(toRead);
1219 }
1220 LogEvent event(std::string(String8(trainName).string()), trainVersionCode, requiresStaging,
1221 rollbackEnabled, requiresLowLatencyMonitor, state, buffer, userId);
1222 mProcessor->OnLogEvent(&event);
1223 StorageManager::writeTrainInfo(trainVersionCode, buffer);
1224 return Status::ok();
1225}
1226
Howard Roa46b6582018-09-18 16:45:02 -07001227hardware::Return<void> StatsService::reportSpeakerImpedance(
1228 const SpeakerImpedance& speakerImpedance) {
1229 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), speakerImpedance);
1230 mProcessor->OnLogEvent(&event);
1231
1232 return hardware::Void();
1233}
1234
1235hardware::Return<void> StatsService::reportHardwareFailed(const HardwareFailed& hardwareFailed) {
1236 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), hardwareFailed);
1237 mProcessor->OnLogEvent(&event);
1238
1239 return hardware::Void();
1240}
1241
1242hardware::Return<void> StatsService::reportPhysicalDropDetected(
1243 const PhysicalDropDetected& physicalDropDetected) {
1244 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), physicalDropDetected);
1245 mProcessor->OnLogEvent(&event);
1246
1247 return hardware::Void();
1248}
1249
1250hardware::Return<void> StatsService::reportChargeCycles(const ChargeCycles& chargeCycles) {
1251 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), chargeCycles);
1252 mProcessor->OnLogEvent(&event);
1253
1254 return hardware::Void();
1255}
1256
1257hardware::Return<void> StatsService::reportBatteryHealthSnapshot(
1258 const BatteryHealthSnapshotArgs& batteryHealthSnapshotArgs) {
1259 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(),
1260 batteryHealthSnapshotArgs);
1261 mProcessor->OnLogEvent(&event);
1262
1263 return hardware::Void();
1264}
1265
1266hardware::Return<void> StatsService::reportSlowIo(const SlowIo& slowIo) {
1267 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), slowIo);
1268 mProcessor->OnLogEvent(&event);
1269
1270 return hardware::Void();
1271}
1272
1273hardware::Return<void> StatsService::reportBatteryCausedShutdown(
1274 const BatteryCausedShutdown& batteryCausedShutdown) {
1275 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), batteryCausedShutdown);
1276 mProcessor->OnLogEvent(&event);
1277
1278 return hardware::Void();
1279}
1280
Maggie Whitefc1aa592018-11-28 21:55:23 -08001281hardware::Return<void> StatsService::reportUsbPortOverheatEvent(
1282 const UsbPortOverheatEvent& usbPortOverheatEvent) {
1283 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), usbPortOverheatEvent);
1284 mProcessor->OnLogEvent(&event);
1285
1286 return hardware::Void();
1287}
1288
Carter Hsub8fd1e92019-01-11 15:24:45 +08001289hardware::Return<void> StatsService::reportSpeechDspStat(
1290 const SpeechDspStat& speechDspStat) {
1291 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), speechDspStat);
1292 mProcessor->OnLogEvent(&event);
1293
1294 return hardware::Void();
1295}
1296
Maggie White58174da2019-01-18 15:23:35 -08001297hardware::Return<void> StatsService::reportVendorAtom(const VendorAtom& vendorAtom) {
1298 std::string reverseDomainName = (std::string) vendorAtom.reverseDomainName;
1299 if (vendorAtom.atomId < 100000 || vendorAtom.atomId >= 200000) {
1300 ALOGE("Atom ID %ld is not a valid vendor atom ID", (long) vendorAtom.atomId);
1301 return hardware::Void();
1302 }
1303 if (reverseDomainName.length() > 50) {
1304 ALOGE("Vendor atom reverse domain name %s is too long.", reverseDomainName.c_str());
1305 return hardware::Void();
1306 }
1307 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), vendorAtom);
1308 mProcessor->OnLogEvent(&event);
1309
1310 return hardware::Void();
1311}
1312
David Chen1d7b0cd2017-11-15 14:20:04 -08001313void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001314 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001315 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1316 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001317 ALOGW("Reset statsd upon system server restarts.");
Yangster-mac892f3d32018-05-02 14:16:48 -07001318 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED);
1319 mProcessor->resetConfigs();
1320 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001321 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1322 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
1323 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001324 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001325}
1326
Yao Chenef99c4f2017-09-22 16:26:54 -07001327} // namespace statsd
1328} // namespace os
1329} // namespace android