blob: 7fecf46c4ca5dc824c3bcf63906f028e0ee43da3 [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>
Tej Singh53f9dee2019-04-30 17:45:54 -070031#include <android-base/strings.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Jeff Sharkey6b649252018-04-16 09:50:22 -060034#include <binder/PermissionController.h>
Chenjie Yu6b1667c2019-01-18 10:09:33 -080035#include <cutils/multiuser.h>
yro87d983c2017-11-14 21:31:43 -080036#include <dirent.h>
David Chen0656b7a2017-09-13 15:53:39 -070037#include <frameworks/base/cmds/statsd/src/statsd_config.pb.h>
Max Dashouk11e0d402019-05-16 16:58:07 -070038#include <frameworks/base/cmds/statsd/src/uid_data.pb.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070039#include <private/android_filesystem_config.h>
Bookatzb223c4e2018-02-01 15:35:04 -080040#include <statslog.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070041#include <stdio.h>
Yao Chen482d2722017-09-12 13:25:43 -070042#include <stdlib.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070043#include <sys/system_properties.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070044#include <unistd.h>
Yao Chena80e5c02018-09-04 13:55:29 -070045#include <utils/Looper.h>
46#include <utils/String16.h>
47#include <chrono>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070048
49using namespace android;
50
Jeff Sharkey6b649252018-04-16 09:50:22 -060051using android::base::StringPrintf;
Bookatzff71cad2018-09-20 17:17:49 -070052using android::util::FIELD_COUNT_REPEATED;
Chenjie Yu6b1667c2019-01-18 10:09:33 -080053using android::util::FIELD_TYPE_INT64;
Bookatzff71cad2018-09-20 17:17:49 -070054using android::util::FIELD_TYPE_MESSAGE;
Joe Onorato99598ee2019-02-11 15:55:13 +000055using android::util::ProtoReader;
Jeff Sharkey6b649252018-04-16 09:50:22 -060056
Bookatz906a35c2017-09-20 15:26:44 -070057namespace android {
58namespace os {
59namespace statsd {
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
Yao Chen0f861862019-03-27 11:51:15 -0700135StatsService::StatsService(const sp<Looper>& handlerLooper, shared_ptr<LogEventQueue> queue)
136 : mAnomalyAlarmMonitor(new AlarmMonitor(
137 MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
138 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
139 if (sc != nullptr) {
140 sc->setAnomalyAlarm(timeMillis);
141 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
142 }
143 },
144 [](const sp<IStatsCompanionService>& sc) {
145 if (sc != nullptr) {
146 sc->cancelAnomalyAlarm();
147 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
148 }
149 })),
150 mPeriodicAlarmMonitor(new AlarmMonitor(
151 MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
152 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
153 if (sc != nullptr) {
154 sc->setAlarmForSubscriberTriggering(timeMillis);
155 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
156 }
157 },
158 [](const sp<IStatsCompanionService>& sc) {
159 if (sc != nullptr) {
160 sc->cancelAlarmForSubscriberTriggering();
161 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
162 }
163 })),
164 mEventQueue(queue) {
Yao Chen4ce07292019-02-13 13:06:36 -0800165 mUidMap = UidMap::getInstance();
Chenjie Yue2219202018-06-08 10:07:51 -0700166 mPullerManager = new StatsPullerManager();
Chenjie Yu80f91122018-01-31 20:24:50 -0800167 StatsPuller::SetUidMap(mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700168 mConfigManager = new ConfigManager();
Chenjie Yue2219202018-06-08 10:07:51 -0700169 mProcessor = new StatsLogProcessor(
170 mUidMap, mPullerManager, mAnomalyAlarmMonitor, mPeriodicAlarmMonitor,
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800171 getElapsedRealtimeNs(),
172 [this](const ConfigKey& key) {
Jeffrey Huangad213742019-12-16 13:50:06 -0800173 sp<IPendingIntentRef> receiver = mConfigManager->GetConfigReceiver(key);
174 if (receiver == nullptr) {
175 VLOG("Could not find a broadcast receiver for %s",
176 key.ToString().c_str());
Chenjie Yue2219202018-06-08 10:07:51 -0700177 return false;
Jeffrey Huangad213742019-12-16 13:50:06 -0800178 } else if (receiver->sendDataBroadcast(
179 mProcessor->getLastReportTimeNs(key)).isOk()) {
Chenjie Yue2219202018-06-08 10:07:51 -0700180 return true;
Jeffrey Huangad213742019-12-16 13:50:06 -0800181 } else {
182 VLOG("Failed to send a broadcast for receiver %s",
183 key.ToString().c_str());
184 return false;
Chenjie Yue2219202018-06-08 10:07:51 -0700185 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800186 },
187 [this](const int& uid, const vector<int64_t>& activeConfigs) {
188 auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
189 sp<IStatsCompanionService> sc = getStatsCompanionService();
190 if (sc == nullptr) {
191 VLOG("Could not access statsCompanion");
192 return false;
193 } else if (receiver == nullptr) {
194 VLOG("Could not find receiver for uid %d", uid);
195 return false;
196 } else {
197 sc->sendActiveConfigsChangedBroadcast(receiver, activeConfigs);
198 VLOG("StatsService::active configs broadcast succeeded for uid %d" , uid);
199 return true;
200 }
Chenjie Yue2219202018-06-08 10:07:51 -0700201 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700202
Tej Singh9ec159a2019-11-14 11:59:48 -0800203 mUidMap->setListener(mProcessor);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700204 mConfigManager->AddListener(mProcessor);
205
206 init_system_properties();
Yao Chen0f861862019-03-27 11:51:15 -0700207
208 if (mEventQueue != nullptr) {
209 std::thread pushedEventThread([this] { readLogs(); });
210 pushedEventThread.detach();
211 }
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700212}
213
Yao Chenef99c4f2017-09-22 16:26:54 -0700214StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700215}
216
Yao Chen0f861862019-03-27 11:51:15 -0700217/* Runs on a dedicated thread to process pushed events. */
218void StatsService::readLogs() {
219 // Read forever..... long live statsd
220 while (1) {
221 // Block until an event is available.
222 auto event = mEventQueue->waitPop();
223 // Pass it to StatsLogProcess to all configs/metrics
224 // At this point, the LogEventQueue is not blocked, so that the socketListener
225 // can read events from the socket and write to buffer to avoid data drop.
226 mProcessor->OnLogEvent(event.get());
227 // The ShellSubscriber is only used by shell for local debugging.
228 if (mShellSubscriber != nullptr) {
229 mShellSubscriber->onLogEvent(*event);
230 }
231 }
232}
233
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700234void StatsService::init_system_properties() {
235 mEngBuild = false;
236 const prop_info* buildType = __system_property_find("ro.build.type");
237 if (buildType != NULL) {
238 __system_property_read_callback(buildType, init_build_type_callback, this);
239 }
David Chen0656b7a2017-09-13 15:53:39 -0700240}
241
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700242void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
243 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700244 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700245 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
246 }
247}
248
249/**
250 * Implement our own because the default binder implementation isn't
251 * properly handling SHELL_COMMAND_TRANSACTION.
252 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700253status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
254 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700255 switch (code) {
256 case SHELL_COMMAND_TRANSACTION: {
257 int in = data.readFileDescriptor();
258 int out = data.readFileDescriptor();
259 int err = data.readFileDescriptor();
260 int argc = data.readInt32();
261 Vector<String8> args;
262 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
263 args.add(String8(data.readString16()));
264 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700265 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
266 sp<IResultReceiver> resultReceiver =
267 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700268
Yao Chena80e5c02018-09-04 13:55:29 -0700269 err = command(in, out, err, args, resultReceiver);
Tej Singhc9250ce2019-09-20 19:28:53 -0700270 if (resultReceiver != nullptr) {
271 resultReceiver->send(err);
272 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700273 return NO_ERROR;
274 }
Jeffrey Huang161c0752019-12-11 14:47:32 -0800275 default: { return BnStatsd::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700276 }
277}
278
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700279/**
Bookatzff71cad2018-09-20 17:17:49 -0700280 * Write data from statsd.
281 * Format for statsdStats: adb shell dumpsys stats --metadata [-v] [--proto]
282 * Format for data report: adb shell dumpsys stats [anything other than --metadata] [--proto]
283 * Anything ending in --proto will be in proto format.
284 * Anything without --metadata as the first argument will be report information.
285 * (bugreports call "adb shell dumpsys stats --dump-priority NORMAL -a --proto")
286 * TODO: Come up with a more robust method of enacting <serviceutils/PriorityDumper.h>.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700287 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700288status_t StatsService::dump(int fd, const Vector<String16>& args) {
Tej Singhdd83d702018-04-10 17:24:50 -0700289 if (!checkCallingPermission(String16(kPermissionDump))) {
290 return PERMISSION_DENIED;
291 }
Bookatzff71cad2018-09-20 17:17:49 -0700292 int lastArg = args.size() - 1;
293 bool asProto = false;
294 if (lastArg >= 0 && !args[lastArg].compare(String16("--proto"))) { // last argument
295 asProto = true;
296 lastArg--;
Yao Chen884c8c12018-01-26 10:36:25 -0800297 }
Bookatzff71cad2018-09-20 17:17:49 -0700298 if (args.size() > 0 && !args[0].compare(String16("--metadata"))) { // first argument
299 // Request is to dump statsd stats.
300 bool verbose = false;
301 if (lastArg >= 0 && !args[lastArg].compare(String16("-v"))) {
302 verbose = true;
303 lastArg--;
304 }
305 dumpStatsdStats(fd, verbose, asProto);
306 } else {
307 // Request is to dump statsd report data.
308 if (asProto) {
309 dumpIncidentSection(fd);
310 } else {
311 dprintf(fd, "Non-proto format of stats data dump not available; see proto version.\n");
312 }
Tej Singh41b3f9a2018-04-03 17:06:35 -0700313 }
Yao Chen884c8c12018-01-26 10:36:25 -0800314
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700315 return NO_ERROR;
316}
317
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700318/**
Tej Singh41b3f9a2018-04-03 17:06:35 -0700319 * Write debugging data about statsd in text or proto format.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700320 */
Bookatzff71cad2018-09-20 17:17:49 -0700321void StatsService::dumpStatsdStats(int out, bool verbose, bool proto) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700322 if (proto) {
323 vector<uint8_t> data;
324 StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
325 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700326 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700327 }
328 } else {
329 StatsdStats::getInstance().dumpStats(out);
330 mProcessor->dumpStates(out, verbose);
331 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700332}
333
334/**
Bookatzff71cad2018-09-20 17:17:49 -0700335 * Write stats report data in StatsDataDumpProto incident section format.
336 */
337void StatsService::dumpIncidentSection(int out) {
338 ProtoOutputStream proto;
339 for (const ConfigKey& configKey : mConfigManager->GetAllConfigKeys()) {
340 uint64_t reportsListToken =
341 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS_LIST);
342 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
343 true /* includeCurrentBucket */, false /* erase_data */,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000344 ADB_DUMP,
345 FAST,
346 &proto);
Bookatzff71cad2018-09-20 17:17:49 -0700347 proto.end(reportsListToken);
348 proto.flush(out);
Bookatzc71d9012018-12-19 12:28:38 -0800349 proto.clear();
Bookatzff71cad2018-09-20 17:17:49 -0700350 }
351}
352
353/**
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700354 * Implementation of the adb shell cmd stats command.
355 */
Yao Chena80e5c02018-09-04 13:55:29 -0700356status_t StatsService::command(int in, int out, int err, Vector<String8>& args,
357 sp<IResultReceiver> resultReceiver) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600358 uid_t uid = IPCThreadState::self()->getCallingUid();
359 if (uid != AID_ROOT && uid != AID_SHELL) {
360 return PERMISSION_DENIED;
361 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700362
363 const int argCount = args.size();
364 if (argCount >= 1) {
365 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700366 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700367 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700368 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700369
David Chende701692017-10-05 13:16:02 -0700370 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800371 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700372 }
Yao Chen729093d2017-10-16 10:33:26 -0700373
374 if (!args[0].compare(String8("dump-report"))) {
Bookatzff71cad2018-09-20 17:17:49 -0700375 return cmd_dump_report(out, args);
Yao Chen729093d2017-10-16 10:33:26 -0700376 }
David Chen1481fe12017-10-16 13:16:34 -0700377
378 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
379 return cmd_print_pulled_metrics(out, args);
380 }
David Chenadaf8b32017-11-03 15:42:08 -0700381
382 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800383 return cmd_trigger_broadcast(out, args);
384 }
385
386 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800387 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700388 }
yro87d983c2017-11-14 21:31:43 -0800389
Yao Chen8d9989b2017-11-18 18:54:50 -0800390 if (!args[0].compare(String8("meminfo"))) {
391 return cmd_dump_memory_info(out);
392 }
yro947fbce2017-11-15 22:50:23 -0800393
394 if (!args[0].compare(String8("write-to-disk"))) {
395 return cmd_write_data_to_disk(out);
396 }
Bookatzb223c4e2018-02-01 15:35:04 -0800397
David Chen0b5c90c2018-01-25 16:51:49 -0800398 if (!args[0].compare(String8("log-app-breadcrumb"))) {
399 return cmd_log_app_breadcrumb(out, args);
Bookatzb223c4e2018-02-01 15:35:04 -0800400 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800401
Tej Singh53f9dee2019-04-30 17:45:54 -0700402 if (!args[0].compare(String8("log-binary-push"))) {
403 return cmd_log_binary_push(out, args);
404 }
405
Chenjie Yufa22d652018-02-05 14:37:48 -0800406 if (!args[0].compare(String8("clear-puller-cache"))) {
407 return cmd_clear_puller_cache(out);
408 }
Yao Chen876889c2018-05-02 11:16:16 -0700409
410 if (!args[0].compare(String8("print-logs"))) {
411 return cmd_print_logs(out, args);
412 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800413 if (!args[0].compare(String8("send-active-configs"))) {
414 return cmd_trigger_active_config_broadcast(out, args);
415 }
Yao Chena80e5c02018-09-04 13:55:29 -0700416 if (!args[0].compare(String8("data-subscribe"))) {
Tej Singhc9250ce2019-09-20 19:28:53 -0700417 {
418 std::lock_guard<std::mutex> lock(mShellSubscriberMutex);
419 if (mShellSubscriber == nullptr) {
420 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
421 }
Yao Chena80e5c02018-09-04 13:55:29 -0700422 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800423 int timeoutSec = -1;
424 if (argCount >= 2) {
425 timeoutSec = atoi(args[1].c_str());
426 }
Tej Singhc9250ce2019-09-20 19:28:53 -0700427 if (resultReceiver == nullptr) {
428 ALOGI("Null resultReceiver given, no subscription will be started");
429 return UNEXPECTED_NULL;
430 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800431 mShellSubscriber->startNewSubscription(in, out, resultReceiver, timeoutSec);
Yao Chena80e5c02018-09-04 13:55:29 -0700432 return NO_ERROR;
433 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700434 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700435
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700436 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700437 return NO_ERROR;
438}
439
Yao Chena80e5c02018-09-04 13:55:29 -0700440void StatsService::print_cmd_help(int out) {
441 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700442 "usage: adb shell cmd stats print-stats-log [tag_required] "
443 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700444 dprintf(out, "\n");
445 dprintf(out, "\n");
446 dprintf(out, "usage: adb shell cmd stats meminfo\n");
447 dprintf(out, "\n");
448 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
449 dprintf(out, " # adb shell stop\n");
450 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
451 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
452 dprintf(out, " # adb shell start\n");
453 dprintf(out, "\n");
454 dprintf(out, "\n");
455 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
456 dprintf(out, "\n");
457 dprintf(out, " Prints the UID, app name, version mapping.\n");
458 dprintf(out, " PKG Optional package name to print the uids of the package\n");
459 dprintf(out, "\n");
460 dprintf(out, "\n");
461 dprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
462 dprintf(out, "\n");
463 dprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
464 dprintf(out, "\n");
465 dprintf(out, "\n");
466 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
467 dprintf(out, "\n");
468 dprintf(out, " Flushes all data on memory to disk.\n");
469 dprintf(out, "\n");
470 dprintf(out, "\n");
471 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
472 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
473 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
474 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
475 dprintf(out, " uid is used.\n");
476 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
477 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
478 dprintf(out, "\n");
479 dprintf(out, "\n");
Tej Singh53f9dee2019-04-30 17:45:54 -0700480 dprintf(out,
481 "usage: adb shell cmd stats log-binary-push NAME VERSION STAGING ROLLBACK_ENABLED "
482 "LOW_LATENCY STATE EXPERIMENT_IDS\n");
483 dprintf(out, " Log a binary push state changed event.\n");
484 dprintf(out, " NAME The train name.\n");
485 dprintf(out, " VERSION The train version code.\n");
486 dprintf(out, " STAGING If this train requires a restart.\n");
487 dprintf(out, " ROLLBACK_ENABLED If rollback should be enabled for this install.\n");
488 dprintf(out, " LOW_LATENCY If the train requires low latency monitoring.\n");
489 dprintf(out, " STATE The status of the train push.\n");
490 dprintf(out, " Integer value of the enum in atoms.proto.\n");
491 dprintf(out, " EXPERIMENT_IDS Comma separated list of experiment ids.\n");
492 dprintf(out, " Leave blank for none.\n");
493 dprintf(out, "\n");
494 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700495 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
496 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
497 dprintf(out, "\n");
498 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
499 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
500 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
501 dprintf(out, "\n");
502 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
503 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
504 dprintf(out, " uid is used.\n");
505 dprintf(out, " NAME The per-uid name to use\n");
506 dprintf(out, "\n");
507 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
508 dprintf(out, "\n be removed from memory and disk!\n");
509 dprintf(out, "\n");
510 dprintf(out,
Bookatz3e906582018-12-10 17:26:58 -0800511 "usage: adb shell cmd stats dump-report [UID] NAME [--keep_data] "
512 "[--include_current_bucket] [--proto]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700513 dprintf(out, " Dump all metric data for a configuration.\n");
514 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
515 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
516 dprintf(out, " calling uid is used.\n");
517 dprintf(out, " NAME The name of the configuration\n");
Bookatz3e906582018-12-10 17:26:58 -0800518 dprintf(out, " --keep_data Do NOT erase the data upon dumping it.\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700519 dprintf(out, " --proto Print proto binary.\n");
520 dprintf(out, "\n");
521 dprintf(out, "\n");
522 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
523 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
524 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
525 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
526 dprintf(out, " calling uid is used.\n");
527 dprintf(out, " NAME The name of the configuration\n");
528 dprintf(out, "\n");
529 dprintf(out, "\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800530 dprintf(out,
531 "usage: adb shell cmd stats send-active-configs [--uid=UID] [--configs] "
532 "[NAME1] [NAME2] [NAME3..]\n");
533 dprintf(out, " Send a broadcast that informs the subscriber of the current active configs.\n");
534 dprintf(out, " --uid=UID The uid of the configurations. It is only possible to pass\n");
535 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
536 dprintf(out, " calling uid is used.\n");
537 dprintf(out, " --configs Send the list of configs in the name list instead of\n");
538 dprintf(out, " the currently active configs\n");
539 dprintf(out, " NAME LIST List of configuration names to be included in the broadcast.\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800540 dprintf(out, "\n");
541 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700542 dprintf(out, "usage: adb shell cmd stats print-stats\n");
543 dprintf(out, " Prints some basic stats.\n");
544 dprintf(out, " --proto Print proto binary instead of string format.\n");
545 dprintf(out, "\n");
546 dprintf(out, "\n");
547 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
548 dprintf(out, " Clear cached puller data.\n");
549 dprintf(out, "\n");
550 dprintf(out, "usage: adb shell cmd stats print-logs\n");
551 dprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700552}
553
Yao Chena80e5c02018-09-04 13:55:29 -0700554status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800555 string name;
556 bool good = false;
557 int uid;
558 const int argCount = args.size();
559 if (argCount == 2) {
560 // Automatically pick the UID
561 uid = IPCThreadState::self()->getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800562 name.assign(args[1].c_str(), args[1].size());
563 good = true;
564 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800565 good = getUidFromArgs(args, 1, uid);
566 if (!good) {
567 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
568 "other UIDs on eng or userdebug builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800569 }
Bookatzd2386572018-12-14 15:53:14 -0800570 name.assign(args[2].c_str(), args[2].size());
David Chen1d7b0cd2017-11-15 14:20:04 -0800571 }
572 if (!good) {
573 print_cmd_help(out);
574 return UNKNOWN_ERROR;
575 }
David Chend37bc232018-04-12 18:05:11 -0700576 ConfigKey key(uid, StrToInt64(name));
Jeffrey Huangad213742019-12-16 13:50:06 -0800577 sp<IPendingIntentRef> receiver = mConfigManager->GetConfigReceiver(key);
578 if (receiver == nullptr) {
579 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str());
580 return UNKNOWN_ERROR;
581 } else if (receiver->sendDataBroadcast(
582 mProcessor->getLastReportTimeNs(key)).isOk()) {
yro74fed972017-11-27 14:42:42 -0800583 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
584 args[2].c_str());
Jeffrey Huangad213742019-12-16 13:50:06 -0800585 } else {
586 VLOG("StatsService::trigger broadcast failed to %s, %s", args[1].c_str(),
587 args[2].c_str());
588 return UNKNOWN_ERROR;
yro4d889e62017-11-17 15:44:48 -0800589 }
David Chenadaf8b32017-11-03 15:42:08 -0700590 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700591}
592
Tej Singh6ede28b2019-01-29 17:06:54 -0800593status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
594 const int argCount = args.size();
595 int uid;
596 vector<int64_t> configIds;
597 if (argCount == 1) {
598 // Automatically pick the uid and send a broadcast that has no active configs.
599 uid = IPCThreadState::self()->getCallingUid();
600 mProcessor->GetActiveConfigs(uid, configIds);
601 } else {
602 int curArg = 1;
603 if(args[curArg].find("--uid=") == 0) {
604 string uidArgStr(args[curArg].c_str());
605 string uidStr = uidArgStr.substr(6);
606 if (!getUidFromString(uidStr.c_str(), uid)) {
607 dprintf(out, "Invalid UID. Note that the config can only be set for "
608 "other UIDs on eng or userdebug builds.\n");
609 return UNKNOWN_ERROR;
610 }
611 curArg++;
612 } else {
613 uid = IPCThreadState::self()->getCallingUid();
614 }
615 if (curArg == argCount || args[curArg] != "--configs") {
616 VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
617 mProcessor->GetActiveConfigs(uid, configIds);
618 } else {
619 // Flag specified, use the given list of configs.
620 curArg++;
621 for (int i = curArg; i < argCount; i++) {
622 char* endp;
623 int64_t configID = strtoll(args[i].c_str(), &endp, 10);
624 if (endp == args[i].c_str() || *endp != '\0') {
625 dprintf(out, "Error parsing config ID.\n");
626 return UNKNOWN_ERROR;
627 }
628 VLOG("Adding config id %ld", static_cast<long>(configID));
629 configIds.push_back(configID);
630 }
631 }
632 }
633 auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
634 sp<IStatsCompanionService> sc = getStatsCompanionService();
635 if (sc == nullptr) {
636 VLOG("Could not access statsCompanion");
637 } else if (receiver == nullptr) {
638 VLOG("Could not find receiver for uid %d", uid);
639 } else {
640 sc->sendActiveConfigsChangedBroadcast(receiver, configIds);
641 VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
642 }
643 return NO_ERROR;
644}
645
Yao Chena80e5c02018-09-04 13:55:29 -0700646status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700647 const int argCount = args.size();
648 if (argCount >= 2) {
649 if (args[1] == "update" || args[1] == "remove") {
650 bool good = false;
651 int uid = -1;
652 string name;
653
654 if (argCount == 3) {
655 // Automatically pick the UID
656 uid = IPCThreadState::self()->getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700657 name.assign(args[2].c_str(), args[2].size());
658 good = true;
659 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800660 good = getUidFromArgs(args, 2, uid);
661 if (!good) {
662 dprintf(err, "Invalid UID. Note that the config can only be set for "
663 "other UIDs on eng or userdebug builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700664 }
Bookatzd2386572018-12-14 15:53:14 -0800665 name.assign(args[3].c_str(), args[3].size());
yroe5f82922018-01-22 18:37:27 -0800666 } else if (argCount == 2 && args[1] == "remove") {
667 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700668 }
669
670 if (!good) {
671 // If arg parsing failed, print the help text and return an error.
672 print_cmd_help(out);
673 return UNKNOWN_ERROR;
674 }
675
676 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800677 char* endp;
678 int64_t configID = strtoll(name.c_str(), &endp, 10);
679 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700680 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800681 return UNKNOWN_ERROR;
682 }
683
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700684 // Read stream into buffer.
685 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700686 if (!android::base::ReadFdToString(in, &buffer)) {
687 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700688 return UNKNOWN_ERROR;
689 }
690
691 // Parse buffer.
692 StatsdConfig config;
693 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700694 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700695 return UNKNOWN_ERROR;
696 }
697
698 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800699 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700700 } else {
yro74fed972017-11-27 14:42:42 -0800701 if (argCount == 2) {
702 cmd_remove_all_configs(out);
703 } else {
704 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800705 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800706 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700707 }
708
709 return NO_ERROR;
710 }
David Chen0656b7a2017-09-13 15:53:39 -0700711 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700712 print_cmd_help(out);
713 return UNKNOWN_ERROR;
714}
715
Bookatzff71cad2018-09-20 17:17:49 -0700716status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700717 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800718 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700719 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800720 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700721 bool includeCurrentBucket = false;
Bookatz3e906582018-12-10 17:26:58 -0800722 bool eraseData = true;
Yao Chen729093d2017-10-16 10:33:26 -0700723 int uid;
724 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800725 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
726 proto = true;
727 argCount -= 1;
728 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700729 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
730 includeCurrentBucket = true;
731 argCount -= 1;
732 }
Bookatz3e906582018-12-10 17:26:58 -0800733 if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
734 eraseData = false;
735 argCount -= 1;
736 }
Yao Chen729093d2017-10-16 10:33:26 -0700737 if (argCount == 2) {
738 // Automatically pick the UID
739 uid = IPCThreadState::self()->getCallingUid();
Yao Chen5154a3792017-10-30 22:57:06 -0700740 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700741 good = true;
742 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800743 good = getUidFromArgs(args, 1, uid);
744 if (!good) {
745 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
746 "other UIDs on eng or userdebug builds.\n");
Yao Chen729093d2017-10-16 10:33:26 -0700747 }
Bookatzd2386572018-12-14 15:53:14 -0800748 name.assign(args[2].c_str(), args[2].size());
Yao Chen729093d2017-10-16 10:33:26 -0700749 }
750 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800751 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800752 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000753 includeCurrentBucket, eraseData, ADB_DUMP,
754 NO_TIME_CONSTRAINTS,
755 &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800756 if (proto) {
757 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700758 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800759 }
760 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700761 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800762 }
Yao Chen729093d2017-10-16 10:33:26 -0700763 return android::OK;
764 } else {
765 // If arg parsing failed, print the help text and return an error.
766 print_cmd_help(out);
767 return UNKNOWN_ERROR;
768 }
769 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700770 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700771 return UNKNOWN_ERROR;
772 }
773}
774
Yao Chena80e5c02018-09-04 13:55:29 -0700775status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700776 int argCount = args.size();
777 bool proto = false;
778 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
779 proto = true;
780 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800781 }
Yao Chenb3561512017-11-21 18:07:17 -0800782 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700783 if (proto) {
784 vector<uint8_t> data;
785 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
786 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700787 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700788 }
789
790 } else {
791 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
792 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700793 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700794 mProcessor->GetMetricsSize(key));
795 }
796 statsdStats.dumpStats(out);
797 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800798 return NO_ERROR;
799}
800
Yao Chena80e5c02018-09-04 13:55:29 -0700801status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800802 if (args.size() > 1) {
803 string pkg;
804 pkg.assign(args[1].c_str(), args[1].size());
805 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700806 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800807 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700808 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800809 }
Yao Chena80e5c02018-09-04 13:55:29 -0700810 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800811 } else {
812 mUidMap->printUidMap(out);
813 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700814 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700815}
816
Yao Chena80e5c02018-09-04 13:55:29 -0700817status_t StatsService::cmd_write_data_to_disk(int out) {
818 dprintf(out, "Writing data to disk\n");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000819 mProcessor->WriteDataToDisk(ADB_DUMP, NO_TIME_CONSTRAINTS);
yro947fbce2017-11-15 22:50:23 -0800820 return NO_ERROR;
821}
822
Yao Chena80e5c02018-09-04 13:55:29 -0700823status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800824 bool good = false;
825 int32_t uid;
826 int32_t label;
827 int32_t state;
828 const int argCount = args.size();
829 if (argCount == 3) {
830 // Automatically pick the UID
831 uid = IPCThreadState::self()->getCallingUid();
832 label = atoi(args[1].c_str());
833 state = atoi(args[2].c_str());
834 good = true;
835 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800836 good = getUidFromArgs(args, 1, uid);
837 if (!good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700838 dprintf(out,
Bookatzd2386572018-12-14 15:53:14 -0800839 "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
840 "done for other UIDs on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800841 }
Bookatzd2386572018-12-14 15:53:14 -0800842 label = atoi(args[2].c_str());
843 state = atoi(args[3].c_str());
Bookatzb223c4e2018-02-01 15:35:04 -0800844 }
845 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700846 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
David Chen0b5c90c2018-01-25 16:51:49 -0800847 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800848 } else {
849 print_cmd_help(out);
850 return UNKNOWN_ERROR;
851 }
852 return NO_ERROR;
853}
854
Tej Singh53f9dee2019-04-30 17:45:54 -0700855status_t StatsService::cmd_log_binary_push(int out, const Vector<String8>& args) {
856 // Security checks are done in the sendBinaryPushStateChanged atom.
857 const int argCount = args.size();
858 if (argCount != 7 && argCount != 8) {
859 dprintf(out, "Incorrect number of argument supplied\n");
860 return UNKNOWN_ERROR;
861 }
862 android::String16 trainName = android::String16(args[1].c_str());
863 int64_t trainVersion = strtoll(args[2].c_str(), nullptr, 10);
864 int options = 0;
865 if (args[3] == "1") {
Jeffrey Huang161c0752019-12-11 14:47:32 -0800866 options = options | IStatsd::FLAG_REQUIRE_STAGING;
Tej Singh53f9dee2019-04-30 17:45:54 -0700867 }
868 if (args[4] == "1") {
Jeffrey Huang161c0752019-12-11 14:47:32 -0800869 options = options | IStatsd::FLAG_ROLLBACK_ENABLED;
Tej Singh53f9dee2019-04-30 17:45:54 -0700870 }
871 if (args[5] == "1") {
Jeffrey Huang161c0752019-12-11 14:47:32 -0800872 options = options | IStatsd::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
Tej Singh53f9dee2019-04-30 17:45:54 -0700873 }
874 int32_t state = atoi(args[6].c_str());
875 vector<int64_t> experimentIds;
876 if (argCount == 8) {
877 vector<string> experimentIdsString = android::base::Split(string(args[7].c_str()), ",");
878 for (string experimentIdString : experimentIdsString) {
879 int64_t experimentId = strtoll(experimentIdString.c_str(), nullptr, 10);
880 experimentIds.push_back(experimentId);
881 }
882 }
883 dprintf(out, "Logging BinaryPushStateChanged\n");
884 sendBinaryPushStateChangedAtom(trainName, trainVersion, options, state, experimentIds);
885 return NO_ERROR;
886}
887
Yao Chena80e5c02018-09-04 13:55:29 -0700888status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700889 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700890 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800891 if (mPullerManager->Pull(s, &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700892 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700893 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700894 }
Yao Chena80e5c02018-09-04 13:55:29 -0700895 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700896 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700897 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700898 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700899}
900
Yao Chena80e5c02018-09-04 13:55:29 -0700901status_t StatsService::cmd_remove_all_configs(int out) {
902 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800903 VLOG("StatsService::cmd_remove_all_configs was called");
904 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800905 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800906 return NO_ERROR;
907}
908
Yao Chena80e5c02018-09-04 13:55:29 -0700909status_t StatsService::cmd_dump_memory_info(int out) {
910 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800911 return NO_ERROR;
912}
913
Yao Chena80e5c02018-09-04 13:55:29 -0700914status_t StatsService::cmd_clear_puller_cache(int out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800915 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800916 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
917 ipc->getCallingPid(), ipc->getCallingUid());
Chenjie Yufa22d652018-02-05 14:37:48 -0800918 if (checkCallingPermission(String16(kPermissionDump))) {
Chenjie Yue2219202018-06-08 10:07:51 -0700919 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700920 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800921 return NO_ERROR;
922 } else {
923 return PERMISSION_DENIED;
924 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800925}
926
Yao Chena80e5c02018-09-04 13:55:29 -0700927status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Yao Chen876889c2018-05-02 11:16:16 -0700928 IPCThreadState* ipc = IPCThreadState::self();
929 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", ipc->getCallingPid(),
930 ipc->getCallingUid());
931 if (checkCallingPermission(String16(kPermissionDump))) {
932 bool enabled = true;
933 if (args.size() >= 2) {
934 enabled = atoi(args[1].c_str()) != 0;
935 }
936 mProcessor->setPrintLogs(enabled);
937 return NO_ERROR;
938 } else {
939 return PERMISSION_DENIED;
940 }
941}
942
Bookatzd2386572018-12-14 15:53:14 -0800943bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800944 return getUidFromString(args[uidArgIndex].c_str(), uid);
945}
946
947bool StatsService::getUidFromString(const char* s, int32_t& uid) {
Bookatzd2386572018-12-14 15:53:14 -0800948 if (*s == '\0') {
949 return false;
950 }
951 char* endc = NULL;
952 int64_t longUid = strtol(s, &endc, 0);
953 if (*endc != '\0') {
954 return false;
955 }
956 int32_t goodUid = static_cast<int32_t>(longUid);
957 if (longUid < 0 || static_cast<uint64_t>(longUid) != static_cast<uid_t>(goodUid)) {
958 return false; // It was not of uid_t type.
959 }
960 uid = goodUid;
961
962 int32_t callingUid = IPCThreadState::self()->getCallingUid();
963 return mEngBuild // UserDebug/EngBuild are allowed to impersonate uids.
964 || (callingUid == goodUid) // Anyone can 'impersonate' themselves.
965 || (callingUid == AID_ROOT && goodUid == AID_SHELL); // ROOT can impersonate SHELL.
966}
967
Max Dashouk11e0d402019-05-16 16:58:07 -0700968Status StatsService::informAllUidData(const ParcelFileDescriptor& fd) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600969 ENFORCE_UID(AID_SYSTEM);
Max Dashouk11e0d402019-05-16 16:58:07 -0700970 // Read stream into buffer.
971 string buffer;
972 if (!android::base::ReadFdToString(fd.get(), &buffer)) {
973 return exception(Status::EX_ILLEGAL_ARGUMENT, "Failed to read all data from the pipe.");
974 }
Jeff Sharkey6b649252018-04-16 09:50:22 -0600975
Max Dashouk11e0d402019-05-16 16:58:07 -0700976 // Parse buffer.
977 UidData uidData;
978 if (!uidData.ParseFromString(buffer)) {
979 return exception(Status::EX_ILLEGAL_ARGUMENT, "Error parsing proto stream for UidData.");
980 }
David Chende701692017-10-05 13:16:02 -0700981
Max Dashouk11e0d402019-05-16 16:58:07 -0700982 vector<String16> versionStrings;
983 vector<String16> installers;
984 vector<String16> packageNames;
985 vector<int32_t> uids;
986 vector<int64_t> versions;
987
988 const auto numEntries = uidData.app_info_size();
989 versionStrings.reserve(numEntries);
990 installers.reserve(numEntries);
991 packageNames.reserve(numEntries);
992 uids.reserve(numEntries);
993 versions.reserve(numEntries);
994
995 for (const auto& appInfo: uidData.app_info()) {
996 packageNames.emplace_back(String16(appInfo.package_name().c_str()));
997 uids.push_back(appInfo.uid());
998 versions.push_back(appInfo.version());
999 versionStrings.emplace_back(String16(appInfo.version_string().c_str()));
1000 installers.emplace_back(String16(appInfo.installer().c_str()));
1001 }
1002
1003 mUidMap->updateMap(getElapsedRealtimeNs(),
1004 uids,
1005 versions,
1006 versionStrings,
1007 packageNames,
1008 installers);
1009
1010 VLOG("StatsService::informAllUidData UidData proto parsed successfully.");
David Chende701692017-10-05 13:16:02 -07001011 return Status::ok();
1012}
1013
dwchen730403e2018-10-29 11:41:56 -07001014Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version,
1015 const String16& version_string, const String16& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001016 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -07001017
Jeff Sharkey6b649252018-04-16 09:50:22 -06001018 VLOG("StatsService::informOnePackage was called");
dwchen730403e2018-10-29 11:41:56 -07001019 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version, version_string, installer);
David Chende701692017-10-05 13:16:02 -07001020 return Status::ok();
1021}
1022
1023Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001024 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -07001025
Jeff Sharkey6b649252018-04-16 09:50:22 -06001026 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -07001027 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -08001028 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -07001029 return Status::ok();
1030}
1031
Yao Chenef99c4f2017-09-22 16:26:54 -07001032Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001033 ENFORCE_UID(AID_SYSTEM);
1034
yro74fed972017-11-27 14:42:42 -08001035 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -07001036 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -08001037 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
1038 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
1039 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -08001040 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -08001041 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -08001042 } else {
1043 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
1044 }
Bookatz1b0b1142017-09-08 11:58:42 -07001045 return Status::ok();
1046}
1047
Yangster-mac932ecec2018-02-01 10:23:52 -08001048Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001049 ENFORCE_UID(AID_SYSTEM);
1050
Yangster-mac932ecec2018-02-01 10:23:52 -08001051 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -07001052 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -08001053 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
1054 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
1055 if (alarmSet.size() > 0) {
1056 VLOG("Found periodic alarm fired.");
1057 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
1058 } else {
1059 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
1060 }
1061 return Status::ok();
1062}
1063
Yao Chenef99c4f2017-09-22 16:26:54 -07001064Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001065 ENFORCE_UID(AID_SYSTEM);
1066
yro74fed972017-11-27 14:42:42 -08001067 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -07001068 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -08001069 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -07001070 return Status::ok();
1071}
1072
Yao Chenef99c4f2017-09-22 16:26:54 -07001073Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001074 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001075
1076 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -08001077 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -07001078 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001079 return Status::ok();
1080}
1081
Yangster-mac892f3d32018-05-02 14:16:48 -07001082Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001083 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -07001084 VLOG("StatsService::informDeviceShutdown");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001085 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001086 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
yro947fbce2017-11-15 22:50:23 -08001087 return Status::ok();
1088}
1089
Yao Chenef99c4f2017-09-22 16:26:54 -07001090void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -07001091 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1092 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -08001093 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -07001094 statsCompanion->statsdReady();
1095 } else {
yro74fed972017-11-27 14:42:42 -08001096 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -07001097 }
1098}
1099
Yao Chenef99c4f2017-09-22 16:26:54 -07001100Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001101 ENFORCE_UID(AID_SYSTEM);
1102
yro74fed972017-11-27 14:42:42 -08001103 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -07001104 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1105 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -07001106 return Status::fromExceptionCode(
1107 Status::EX_NULL_POINTER,
1108 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -07001109 }
yro74fed972017-11-27 14:42:42 -08001110 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001111 IInterface::asBinder(statsCompanion)->linkToDeath(this);
Chenjie Yue2219202018-06-08 10:07:51 -07001112 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -08001113 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
1114 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -08001115 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -07001116 return Status::ok();
1117}
1118
Joe Onorato9fc9edf2017-10-15 20:08:52 -07001119void StatsService::Startup() {
1120 mConfigManager->Startup();
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001121 mProcessor->LoadActiveConfigsFromDisk();
Bookatz906a35c2017-09-20 15:26:44 -07001122}
1123
Yangster-mac97e7d202018-10-09 11:05:39 -07001124void StatsService::Terminate() {
1125 ALOGI("StatsService::Terminating");
1126 if (mProcessor != nullptr) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001127 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001128 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
Yangster-mac97e7d202018-10-09 11:05:39 -07001129 }
1130}
1131
Yao Chen0f861862019-03-27 11:51:15 -07001132// Test only interface!!!
Yao Chen3ff3a492018-08-06 16:17:37 -07001133void StatsService::OnLogEvent(LogEvent* event) {
1134 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -07001135 if (mShellSubscriber != nullptr) {
1136 mShellSubscriber->onLogEvent(*event);
1137 }
Bookatz906a35c2017-09-20 15:26:44 -07001138}
1139
Jeff Sharkey6b649252018-04-16 09:50:22 -06001140Status StatsService::getData(int64_t key, const String16& packageName, vector<uint8_t>* output) {
1141 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1142
David Chenadaf8b32017-11-03 15:42:08 -07001143 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -08001144 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001145 ConfigKey configKey(ipc->getCallingUid(), key);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001146 // The dump latency does not matter here since we do not include the current bucket, we do not
1147 // need to pull any new data anyhow.
David Chen56ae0d92018-05-11 16:00:22 -07001148 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001149 true /* erase_data */, GET_DATA_CALLED, FAST, output);
Bookatz4f716292018-04-10 17:15:12 -07001150 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001151}
1152
Jeff Sharkey6b649252018-04-16 09:50:22 -06001153Status StatsService::getMetadata(const String16& packageName, vector<uint8_t>* output) {
1154 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1155
David Chen2e8f3802017-11-22 10:56:48 -08001156 IPCThreadState* ipc = IPCThreadState::self();
1157 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
1158 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001159 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
1160 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -08001161}
1162
Jeff Sharkey6b649252018-04-16 09:50:22 -06001163Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
1164 const String16& packageName) {
1165 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1166
David Chenadaf8b32017-11-03 15:42:08 -07001167 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -07001168 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -08001169 return Status::ok();
1170 } else {
Bookatz4f716292018-04-10 17:15:12 -07001171 ALOGE("Could not parse malformatted StatsdConfig");
1172 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
1173 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -08001174 }
1175}
1176
David Chen9fdd4032018-03-20 14:38:56 -07001177bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
1178 ConfigKey configKey(uid, key);
1179 StatsdConfig cfg;
1180 if (config.size() > 0) { // If the config is empty, skip parsing.
1181 if (!cfg.ParseFromArray(&config[0], config.size())) {
1182 return false;
1183 }
1184 }
1185 mConfigManager->UpdateConfig(configKey, cfg);
1186 return true;
1187}
1188
Jeffrey Huangad213742019-12-16 13:50:06 -08001189Status StatsService::removeDataFetchOperation(int64_t key,
1190 const int32_t callingUid) {
1191 ENFORCE_UID(AID_SYSTEM);
1192 ConfigKey configKey(callingUid, key);
Bookatz4f716292018-04-10 17:15:12 -07001193 mConfigManager->RemoveConfigReceiver(configKey);
1194 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -08001195}
1196
Jeff Sharkey6b649252018-04-16 09:50:22 -06001197Status StatsService::setDataFetchOperation(int64_t key,
Jeffrey Huangad213742019-12-16 13:50:06 -08001198 const sp<IPendingIntentRef>& pir,
1199 const int32_t callingUid) {
1200 ENFORCE_UID(AID_SYSTEM);
Jeff Sharkey6b649252018-04-16 09:50:22 -06001201
Jeffrey Huangad213742019-12-16 13:50:06 -08001202 ConfigKey configKey(callingUid, key);
1203 mConfigManager->SetConfigReceiver(configKey, pir);
David Chen48944902018-05-03 10:29:11 -07001204 if (StorageManager::hasConfigMetricsReport(configKey)) {
1205 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
1206 configKey.ToString().c_str());
1207 mProcessor->noteOnDiskData(configKey);
1208 }
Bookatz4f716292018-04-10 17:15:12 -07001209 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001210}
1211
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001212Status StatsService::setActiveConfigsChangedOperation(const sp<android::IBinder>& intentSender,
1213 const String16& packageName,
1214 vector<int64_t>* output) {
1215 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1216
1217 IPCThreadState* ipc = IPCThreadState::self();
Tej Singh6ede28b2019-01-29 17:06:54 -08001218 int uid = ipc->getCallingUid();
1219 mConfigManager->SetActiveConfigsChangedReceiver(uid, intentSender);
1220 if (output != nullptr) {
1221 mProcessor->GetActiveConfigs(uid, *output);
1222 } else {
1223 ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
1224 }
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001225 return Status::ok();
1226}
1227
1228Status StatsService::removeActiveConfigsChangedOperation(const String16& packageName) {
1229 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1230
1231 IPCThreadState* ipc = IPCThreadState::self();
1232 mConfigManager->RemoveActiveConfigsChangedReceiver(ipc->getCallingUid());
1233 return Status::ok();
1234}
1235
Jeff Sharkey6b649252018-04-16 09:50:22 -06001236Status StatsService::removeConfiguration(int64_t key, const String16& packageName) {
1237 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1238
Bookatz4f716292018-04-10 17:15:12 -07001239 IPCThreadState* ipc = IPCThreadState::self();
1240 ConfigKey configKey(ipc->getCallingUid(), key);
1241 mConfigManager->RemoveConfig(configKey);
1242 SubscriberReporter::getInstance().removeConfig(configKey);
1243 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001244}
1245
Bookatzc6977972018-01-16 16:55:05 -08001246Status StatsService::setBroadcastSubscriber(int64_t configId,
1247 int64_t subscriberId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001248 const sp<android::IBinder>& intentSender,
1249 const String16& packageName) {
1250 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1251
Bookatzc6977972018-01-16 16:55:05 -08001252 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001253 IPCThreadState* ipc = IPCThreadState::self();
1254 ConfigKey configKey(ipc->getCallingUid(), configId);
1255 SubscriberReporter::getInstance()
1256 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
1257 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001258}
1259
1260Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001261 int64_t subscriberId,
1262 const String16& packageName) {
1263 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1264
Bookatzc6977972018-01-16 16:55:05 -08001265 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001266 IPCThreadState* ipc = IPCThreadState::self();
1267 ConfigKey configKey(ipc->getCallingUid(), configId);
1268 SubscriberReporter::getInstance()
1269 .unsetBroadcastSubscriber(configKey, subscriberId);
1270 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001271}
1272
yrobe6d7f92018-05-04 13:02:53 -07001273Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
1274 // Permission check not necessary as it's meant for applications to write to
1275 // statsd.
1276 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
Jeff Sharkey6bd21572019-11-15 20:45:33 -07001277 (int32_t) IPCThreadState::self()->getCallingUid(), label,
yrobe6d7f92018-05-04 13:02:53 -07001278 state);
1279 return Status::ok();
1280}
1281
Tej Singha0c89dd2019-01-25 16:39:18 -08001282Status StatsService::registerPullerCallback(int32_t atomTag,
1283 const sp<android::os::IStatsPullerCallback>& pullerCallback,
1284 const String16& packageName) {
1285 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1286
1287 VLOG("StatsService::registerPullerCallback called.");
1288 mPullerManager->RegisterPullerCallback(atomTag, pullerCallback);
1289 return Status::ok();
1290}
1291
Tej Singh59184292019-10-11 11:07:06 -07001292Status StatsService::registerPullAtomCallback(int32_t uid, int32_t atomTag, int64_t coolDownNs,
1293 int64_t timeoutNs, const std::vector<int32_t>& additiveFields,
1294 const sp<android::os::IPullAtomCallback>& pullerCallback) {
Tej Singh6a5c9432019-10-11 11:07:06 -07001295 ENFORCE_UID(AID_SYSTEM);
1296
Tej Singhb7802512019-12-04 17:57:04 -08001297 VLOG("StatsService::registerPullAtomCallback called.");
1298 mPullerManager->RegisterPullAtomCallback(uid, atomTag, coolDownNs, timeoutNs, additiveFields,
1299 pullerCallback);
1300 return Status::ok();
1301}
1302
1303Status StatsService::registerNativePullAtomCallback(int32_t atomTag, int64_t coolDownNs,
1304 int64_t timeoutNs, const std::vector<int32_t>& additiveFields,
1305 const sp<android::os::IPullAtomCallback>& pullerCallback) {
1306
1307 VLOG("StatsService::registerNativePullAtomCallback called.");
1308 int32_t uid = IPCThreadState::self()->getCallingUid();
Tej Singh6a5c9432019-10-11 11:07:06 -07001309 mPullerManager->RegisterPullAtomCallback(uid, atomTag, coolDownNs, timeoutNs, additiveFields,
1310 pullerCallback);
Tej Singh59184292019-10-11 11:07:06 -07001311 return Status::ok();
1312}
1313
Tej Singha0c89dd2019-01-25 16:39:18 -08001314Status StatsService::unregisterPullerCallback(int32_t atomTag, const String16& packageName) {
1315 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1316
1317 VLOG("StatsService::unregisterPullerCallback called.");
1318 mPullerManager->UnregisterPullerCallback(atomTag);
1319 return Status::ok();
1320}
1321
Tej Singhfa1c1372019-12-05 20:36:54 -08001322Status StatsService::unregisterPullAtomCallback(int32_t uid, int32_t atomTag) {
1323 ENFORCE_UID(AID_SYSTEM);
1324 VLOG("StatsService::unregisterPullAtomCallback called.");
1325 mPullerManager->UnregisterPullAtomCallback(uid, atomTag);
1326 return Status::ok();
1327}
1328
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001329Status StatsService::sendBinaryPushStateChangedAtom(const android::String16& trainNameIn,
1330 const int64_t trainVersionCodeIn,
1331 const int options,
1332 const int32_t state,
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001333 const std::vector<int64_t>& experimentIdsIn) {
Tej Singh53f9dee2019-04-30 17:45:54 -07001334 // Note: We skip the usage stats op check here since we do not have a package name.
1335 // This is ok since we are overloading the usage_stats permission.
1336 // This method only sends data, it does not receive it.
1337 pid_t pid = IPCThreadState::self()->getCallingPid();
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001338 uid_t uid = IPCThreadState::self()->getCallingUid();
Tej Singh73f8e9b2019-05-19 16:52:38 -07001339 // Root, system, and shell always have access
Tej Singh53f9dee2019-04-30 17:45:54 -07001340 if (uid != AID_ROOT && uid != AID_SYSTEM && uid != AID_SHELL) {
1341 // Caller must be granted these permissions
1342 if (!checkCallingPermission(String16(kPermissionDump))) {
1343 return exception(binder::Status::EX_SECURITY,
1344 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1345 kPermissionDump));
1346 }
1347 if (!checkCallingPermission(String16(kPermissionUsage))) {
1348 return exception(binder::Status::EX_SECURITY,
1349 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1350 kPermissionUsage));
1351 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001352 }
1353
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001354 bool readTrainInfoSuccess = false;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001355 InstallTrainInfo trainInfoOnDisk;
1356 readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfoOnDisk);
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001357
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001358 bool resetExperimentIds = false;
1359 int64_t trainVersionCode = trainVersionCodeIn;
1360 std::string trainNameUtf8 = std::string(String8(trainNameIn).string());
1361 if (readTrainInfoSuccess) {
1362 // Keep the old train version if we received an empty version.
1363 if (trainVersionCodeIn == -1) {
1364 trainVersionCode = trainInfoOnDisk.trainVersionCode;
1365 } else if (trainVersionCodeIn != trainInfoOnDisk.trainVersionCode) {
1366 // Reset experiment ids if we receive a new non-empty train version.
1367 resetExperimentIds = true;
1368 }
1369
1370 // Keep the old train name if we received an empty train name.
1371 if (trainNameUtf8.size() == 0) {
1372 trainNameUtf8 = trainInfoOnDisk.trainName;
1373 } else if (trainNameUtf8 != trainInfoOnDisk.trainName) {
1374 // Reset experiment ids if we received a new valid train name.
1375 resetExperimentIds = true;
1376 }
1377
1378 // Reset if we received a different experiment id.
1379 if (!experimentIdsIn.empty() &&
1380 (trainInfoOnDisk.experimentIds.empty() ||
1381 experimentIdsIn[0] != trainInfoOnDisk.experimentIds[0])) {
1382 resetExperimentIds = true;
1383 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001384 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001385
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001386 // Find the right experiment IDs
1387 std::vector<int64_t> experimentIds;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001388 if (resetExperimentIds || !readTrainInfoSuccess) {
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001389 experimentIds = experimentIdsIn;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001390 } else {
1391 experimentIds = trainInfoOnDisk.experimentIds;
1392 }
1393
1394 if (!experimentIds.empty()) {
1395 int64_t firstId = experimentIds[0];
1396 switch (state) {
1397 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALL_SUCCESS:
1398 experimentIds.push_back(firstId + 1);
1399 break;
1400 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_INITIATED:
1401 experimentIds.push_back(firstId + 2);
1402 break;
1403 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_SUCCESS:
1404 experimentIds.push_back(firstId + 3);
1405 break;
1406 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001407 }
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001408
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001409 // Flatten the experiment IDs to proto
1410 vector<uint8_t> experimentIdsProtoBuffer;
1411 writeExperimentIdsToProto(experimentIds, &experimentIdsProtoBuffer);
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001412 StorageManager::writeTrainInfo(trainVersionCode, trainNameUtf8, state, experimentIds);
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001413
1414 userid_t userId = multiuser_get_user_id(uid);
Jeffrey Huang161c0752019-12-11 14:47:32 -08001415 bool requiresStaging = options & IStatsd::FLAG_REQUIRE_STAGING;
1416 bool rollbackEnabled = options & IStatsd::FLAG_ROLLBACK_ENABLED;
1417 bool requiresLowLatencyMonitor = options & IStatsd::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001418 LogEvent event(trainNameUtf8, trainVersionCode, requiresStaging, rollbackEnabled,
1419 requiresLowLatencyMonitor, state, experimentIdsProtoBuffer, userId);
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001420 mProcessor->OnLogEvent(&event);
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001421 return Status::ok();
1422}
1423
Tej Singh73f8e9b2019-05-19 16:52:38 -07001424Status StatsService::sendWatchdogRollbackOccurredAtom(const int32_t rollbackTypeIn,
1425 const android::String16& packageNameIn,
Gavin Corkerydd1daba2019-11-27 19:11:13 +00001426 const int64_t packageVersionCodeIn,
1427 const int32_t rollbackReasonIn,
1428 const android::String16&
1429 failingPackageNameIn) {
Tej Singh73f8e9b2019-05-19 16:52:38 -07001430 // Note: We skip the usage stats op check here since we do not have a package name.
1431 // This is ok since we are overloading the usage_stats permission.
1432 // This method only sends data, it does not receive it.
1433 pid_t pid = IPCThreadState::self()->getCallingPid();
1434 uid_t uid = IPCThreadState::self()->getCallingUid();
1435 // Root, system, and shell always have access
1436 if (uid != AID_ROOT && uid != AID_SYSTEM && uid != AID_SHELL) {
1437 // Caller must be granted these permissions
1438 if (!checkCallingPermission(String16(kPermissionDump))) {
1439 return exception(binder::Status::EX_SECURITY,
1440 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1441 kPermissionDump));
1442 }
1443 if (!checkCallingPermission(String16(kPermissionUsage))) {
1444 return exception(binder::Status::EX_SECURITY,
1445 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1446 kPermissionUsage));
1447 }
1448 }
1449
1450 android::util::stats_write(android::util::WATCHDOG_ROLLBACK_OCCURRED,
Gavin Corkerydd1daba2019-11-27 19:11:13 +00001451 rollbackTypeIn, String8(packageNameIn).string(), packageVersionCodeIn,
1452 rollbackReasonIn, String8(failingPackageNameIn).string());
Tej Singh73f8e9b2019-05-19 16:52:38 -07001453
1454 // Fast return to save disk read.
1455 if (rollbackTypeIn != android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS
1456 && rollbackTypeIn !=
1457 android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE) {
1458 return Status::ok();
1459 }
1460
1461 bool readTrainInfoSuccess = false;
1462 InstallTrainInfo trainInfoOnDisk;
1463 readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfoOnDisk);
1464
1465 if (!readTrainInfoSuccess) {
1466 return Status::ok();
1467 }
1468 std::vector<int64_t> experimentIds = trainInfoOnDisk.experimentIds;
1469 if (experimentIds.empty()) {
1470 return Status::ok();
1471 }
1472 switch (rollbackTypeIn) {
1473 case android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE:
1474 experimentIds.push_back(experimentIds[0] + 4);
1475 break;
1476 case android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS:
1477 experimentIds.push_back(experimentIds[0] + 5);
1478 break;
1479 }
1480 StorageManager::writeTrainInfo(trainInfoOnDisk.trainVersionCode, trainInfoOnDisk.trainName,
1481 trainInfoOnDisk.status, experimentIds);
1482 return Status::ok();
1483}
1484
1485
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001486Status StatsService::getRegisteredExperimentIds(std::vector<int64_t>* experimentIdsOut) {
1487 uid_t uid = IPCThreadState::self()->getCallingUid();
1488
1489 // Caller must be granted these permissions
1490 if (!checkCallingPermission(String16(kPermissionDump))) {
1491 return exception(binder::Status::EX_SECURITY,
1492 StringPrintf("UID %d lacks permission %s", uid, kPermissionDump));
1493 }
1494 if (!checkCallingPermission(String16(kPermissionUsage))) {
1495 return exception(binder::Status::EX_SECURITY,
1496 StringPrintf("UID %d lacks permission %s", uid, kPermissionUsage));
1497 }
1498 // TODO: add verifier permission
1499
1500 // Read the latest train info
1501 InstallTrainInfo trainInfo;
1502 if (!StorageManager::readTrainInfo(trainInfo)) {
1503 // No train info means no experiment IDs, return an empty list
1504 experimentIdsOut->clear();
1505 return Status::ok();
1506 }
1507
1508 // Copy the experiment IDs to the out vector
1509 experimentIdsOut->assign(trainInfo.experimentIds.begin(), trainInfo.experimentIds.end());
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001510 return Status::ok();
1511}
1512
Howard Roa46b6582018-09-18 16:45:02 -07001513hardware::Return<void> StatsService::reportSpeakerImpedance(
1514 const SpeakerImpedance& speakerImpedance) {
Tej Singh8928ed72019-02-22 19:06:22 -08001515 android::util::stats_write(android::util::SPEAKER_IMPEDANCE_REPORTED,
1516 speakerImpedance.speakerLocation, speakerImpedance.milliOhms);
Howard Roa46b6582018-09-18 16:45:02 -07001517
1518 return hardware::Void();
1519}
1520
1521hardware::Return<void> StatsService::reportHardwareFailed(const HardwareFailed& hardwareFailed) {
Tej Singh8928ed72019-02-22 19:06:22 -08001522 android::util::stats_write(android::util::HARDWARE_FAILED, int32_t(hardwareFailed.hardwareType),
1523 hardwareFailed.hardwareLocation, int32_t(hardwareFailed.errorCode));
Howard Roa46b6582018-09-18 16:45:02 -07001524
1525 return hardware::Void();
1526}
1527
1528hardware::Return<void> StatsService::reportPhysicalDropDetected(
1529 const PhysicalDropDetected& physicalDropDetected) {
Tej Singh8928ed72019-02-22 19:06:22 -08001530 android::util::stats_write(android::util::PHYSICAL_DROP_DETECTED,
1531 int32_t(physicalDropDetected.confidencePctg), physicalDropDetected.accelPeak,
1532 physicalDropDetected.freefallDuration);
Howard Roa46b6582018-09-18 16:45:02 -07001533
1534 return hardware::Void();
1535}
1536
1537hardware::Return<void> StatsService::reportChargeCycles(const ChargeCycles& chargeCycles) {
Tej Singh8928ed72019-02-22 19:06:22 -08001538 std::vector<int32_t> buckets = chargeCycles.cycleBucket;
1539 int initialSize = buckets.size();
1540 for (int i = 0; i < 10 - initialSize; i++) {
1541 buckets.push_back(-1); // Push -1 for buckets that do not exist.
1542 }
1543 android::util::stats_write(android::util::CHARGE_CYCLES_REPORTED, buckets[0], buckets[1],
1544 buckets[2], buckets[3], buckets[4], buckets[5], buckets[6], buckets[7], buckets[8],
1545 buckets[9]);
Howard Roa46b6582018-09-18 16:45:02 -07001546
1547 return hardware::Void();
1548}
1549
1550hardware::Return<void> StatsService::reportBatteryHealthSnapshot(
1551 const BatteryHealthSnapshotArgs& batteryHealthSnapshotArgs) {
Tej Singh8928ed72019-02-22 19:06:22 -08001552 android::util::stats_write(android::util::BATTERY_HEALTH_SNAPSHOT,
1553 int32_t(batteryHealthSnapshotArgs.type), batteryHealthSnapshotArgs.temperatureDeciC,
1554 batteryHealthSnapshotArgs.voltageMicroV, batteryHealthSnapshotArgs.currentMicroA,
1555 batteryHealthSnapshotArgs.openCircuitVoltageMicroV,
1556 batteryHealthSnapshotArgs.resistanceMicroOhm, batteryHealthSnapshotArgs.levelPercent);
Howard Roa46b6582018-09-18 16:45:02 -07001557
1558 return hardware::Void();
1559}
1560
1561hardware::Return<void> StatsService::reportSlowIo(const SlowIo& slowIo) {
Tej Singh8928ed72019-02-22 19:06:22 -08001562 android::util::stats_write(android::util::SLOW_IO, int32_t(slowIo.operation), slowIo.count);
Howard Roa46b6582018-09-18 16:45:02 -07001563
1564 return hardware::Void();
1565}
1566
1567hardware::Return<void> StatsService::reportBatteryCausedShutdown(
1568 const BatteryCausedShutdown& batteryCausedShutdown) {
Tej Singh8928ed72019-02-22 19:06:22 -08001569 android::util::stats_write(android::util::BATTERY_CAUSED_SHUTDOWN,
1570 batteryCausedShutdown.voltageMicroV);
Howard Roa46b6582018-09-18 16:45:02 -07001571
1572 return hardware::Void();
1573}
1574
Maggie Whitefc1aa592018-11-28 21:55:23 -08001575hardware::Return<void> StatsService::reportUsbPortOverheatEvent(
1576 const UsbPortOverheatEvent& usbPortOverheatEvent) {
Tej Singh8928ed72019-02-22 19:06:22 -08001577 android::util::stats_write(android::util::USB_PORT_OVERHEAT_EVENT_REPORTED,
1578 usbPortOverheatEvent.plugTemperatureDeciC, usbPortOverheatEvent.maxTemperatureDeciC,
1579 usbPortOverheatEvent.timeToOverheat, usbPortOverheatEvent.timeToHysteresis,
1580 usbPortOverheatEvent.timeToInactive);
Maggie Whitefc1aa592018-11-28 21:55:23 -08001581
1582 return hardware::Void();
1583}
1584
Carter Hsub8fd1e92019-01-11 15:24:45 +08001585hardware::Return<void> StatsService::reportSpeechDspStat(
1586 const SpeechDspStat& speechDspStat) {
Tej Singh8928ed72019-02-22 19:06:22 -08001587 android::util::stats_write(android::util::SPEECH_DSP_STAT_REPORTED,
1588 speechDspStat.totalUptimeMillis, speechDspStat.totalDowntimeMillis,
1589 speechDspStat.totalCrashCount, speechDspStat.totalRecoverCount);
Carter Hsub8fd1e92019-01-11 15:24:45 +08001590
1591 return hardware::Void();
1592}
1593
Maggie White58174da2019-01-18 15:23:35 -08001594hardware::Return<void> StatsService::reportVendorAtom(const VendorAtom& vendorAtom) {
1595 std::string reverseDomainName = (std::string) vendorAtom.reverseDomainName;
1596 if (vendorAtom.atomId < 100000 || vendorAtom.atomId >= 200000) {
1597 ALOGE("Atom ID %ld is not a valid vendor atom ID", (long) vendorAtom.atomId);
1598 return hardware::Void();
1599 }
1600 if (reverseDomainName.length() > 50) {
1601 ALOGE("Vendor atom reverse domain name %s is too long.", reverseDomainName.c_str());
1602 return hardware::Void();
1603 }
1604 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), vendorAtom);
1605 mProcessor->OnLogEvent(&event);
1606
1607 return hardware::Void();
1608}
1609
David Chen1d7b0cd2017-11-15 14:20:04 -08001610void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001611 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001612 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1613 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001614 ALOGW("Reset statsd upon system server restarts.");
Tej Singhf53d4452019-05-09 18:17:59 -07001615 int64_t systemServerRestartNs = getElapsedRealtimeNs();
1616 ProtoOutputStream proto;
1617 mProcessor->WriteActiveConfigsToProtoOutputStream(systemServerRestartNs,
1618 STATSCOMPANION_DIED, &proto);
1619
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001620 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED, FAST);
Yangster-mac892f3d32018-05-02 14:16:48 -07001621 mProcessor->resetConfigs();
Tej Singhf53d4452019-05-09 18:17:59 -07001622
1623 std::string serializedActiveConfigs;
1624 if (proto.serializeToString(&serializedActiveConfigs)) {
1625 ActiveConfigList activeConfigs;
1626 if (activeConfigs.ParseFromString(serializedActiveConfigs)) {
1627 mProcessor->SetConfigsActiveState(activeConfigs, systemServerRestartNs);
1628 }
1629 }
Yangster-mac892f3d32018-05-02 14:16:48 -07001630 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001631 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1632 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
1633 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001634 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001635}
1636
Yao Chenef99c4f2017-09-22 16:26:54 -07001637} // namespace statsd
1638} // namespace os
1639} // namespace android