blob: bb3a094af34a17216329340aaffa67982e78b74d [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) {
Chenjie Yue2219202018-06-08 10:07:51 -0700173 sp<IStatsCompanionService> sc = getStatsCompanionService();
174 auto receiver = mConfigManager->GetConfigReceiver(key);
175 if (sc == nullptr) {
176 VLOG("Could not find StatsCompanionService");
177 return false;
178 } else if (receiver == nullptr) {
179 VLOG("Statscompanion could not find a broadcast receiver for %s",
180 key.ToString().c_str());
181 return false;
182 } else {
183 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
184 return true;
185 }
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));
577 auto receiver = mConfigManager->GetConfigReceiver(key);
yro4d889e62017-11-17 15:44:48 -0800578 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen661f7912018-01-22 17:46:24 -0800579 if (sc == nullptr) {
580 VLOG("Could not access statsCompanion");
581 } else if (receiver == nullptr) {
582 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str())
583 } else {
David Chend37bc232018-04-12 18:05:11 -0700584 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
yro74fed972017-11-27 14:42:42 -0800585 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
586 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800587 }
588
David Chenadaf8b32017-11-03 15:42:08 -0700589 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700590}
591
Tej Singh6ede28b2019-01-29 17:06:54 -0800592status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
593 const int argCount = args.size();
594 int uid;
595 vector<int64_t> configIds;
596 if (argCount == 1) {
597 // Automatically pick the uid and send a broadcast that has no active configs.
598 uid = IPCThreadState::self()->getCallingUid();
599 mProcessor->GetActiveConfigs(uid, configIds);
600 } else {
601 int curArg = 1;
602 if(args[curArg].find("--uid=") == 0) {
603 string uidArgStr(args[curArg].c_str());
604 string uidStr = uidArgStr.substr(6);
605 if (!getUidFromString(uidStr.c_str(), uid)) {
606 dprintf(out, "Invalid UID. Note that the config can only be set for "
607 "other UIDs on eng or userdebug builds.\n");
608 return UNKNOWN_ERROR;
609 }
610 curArg++;
611 } else {
612 uid = IPCThreadState::self()->getCallingUid();
613 }
614 if (curArg == argCount || args[curArg] != "--configs") {
615 VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
616 mProcessor->GetActiveConfigs(uid, configIds);
617 } else {
618 // Flag specified, use the given list of configs.
619 curArg++;
620 for (int i = curArg; i < argCount; i++) {
621 char* endp;
622 int64_t configID = strtoll(args[i].c_str(), &endp, 10);
623 if (endp == args[i].c_str() || *endp != '\0') {
624 dprintf(out, "Error parsing config ID.\n");
625 return UNKNOWN_ERROR;
626 }
627 VLOG("Adding config id %ld", static_cast<long>(configID));
628 configIds.push_back(configID);
629 }
630 }
631 }
632 auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
633 sp<IStatsCompanionService> sc = getStatsCompanionService();
634 if (sc == nullptr) {
635 VLOG("Could not access statsCompanion");
636 } else if (receiver == nullptr) {
637 VLOG("Could not find receiver for uid %d", uid);
638 } else {
639 sc->sendActiveConfigsChangedBroadcast(receiver, configIds);
640 VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
641 }
642 return NO_ERROR;
643}
644
Yao Chena80e5c02018-09-04 13:55:29 -0700645status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700646 const int argCount = args.size();
647 if (argCount >= 2) {
648 if (args[1] == "update" || args[1] == "remove") {
649 bool good = false;
650 int uid = -1;
651 string name;
652
653 if (argCount == 3) {
654 // Automatically pick the UID
655 uid = IPCThreadState::self()->getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700656 name.assign(args[2].c_str(), args[2].size());
657 good = true;
658 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800659 good = getUidFromArgs(args, 2, uid);
660 if (!good) {
661 dprintf(err, "Invalid UID. Note that the config can only be set for "
662 "other UIDs on eng or userdebug builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700663 }
Bookatzd2386572018-12-14 15:53:14 -0800664 name.assign(args[3].c_str(), args[3].size());
yroe5f82922018-01-22 18:37:27 -0800665 } else if (argCount == 2 && args[1] == "remove") {
666 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700667 }
668
669 if (!good) {
670 // If arg parsing failed, print the help text and return an error.
671 print_cmd_help(out);
672 return UNKNOWN_ERROR;
673 }
674
675 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800676 char* endp;
677 int64_t configID = strtoll(name.c_str(), &endp, 10);
678 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700679 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800680 return UNKNOWN_ERROR;
681 }
682
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700683 // Read stream into buffer.
684 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700685 if (!android::base::ReadFdToString(in, &buffer)) {
686 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700687 return UNKNOWN_ERROR;
688 }
689
690 // Parse buffer.
691 StatsdConfig config;
692 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700693 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700694 return UNKNOWN_ERROR;
695 }
696
697 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800698 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700699 } else {
yro74fed972017-11-27 14:42:42 -0800700 if (argCount == 2) {
701 cmd_remove_all_configs(out);
702 } else {
703 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800704 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800705 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700706 }
707
708 return NO_ERROR;
709 }
David Chen0656b7a2017-09-13 15:53:39 -0700710 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700711 print_cmd_help(out);
712 return UNKNOWN_ERROR;
713}
714
Bookatzff71cad2018-09-20 17:17:49 -0700715status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700716 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800717 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700718 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800719 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700720 bool includeCurrentBucket = false;
Bookatz3e906582018-12-10 17:26:58 -0800721 bool eraseData = true;
Yao Chen729093d2017-10-16 10:33:26 -0700722 int uid;
723 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800724 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
725 proto = true;
726 argCount -= 1;
727 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700728 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
729 includeCurrentBucket = true;
730 argCount -= 1;
731 }
Bookatz3e906582018-12-10 17:26:58 -0800732 if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
733 eraseData = false;
734 argCount -= 1;
735 }
Yao Chen729093d2017-10-16 10:33:26 -0700736 if (argCount == 2) {
737 // Automatically pick the UID
738 uid = IPCThreadState::self()->getCallingUid();
Yao Chen5154a372017-10-30 22:57:06 -0700739 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700740 good = true;
741 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800742 good = getUidFromArgs(args, 1, uid);
743 if (!good) {
744 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
745 "other UIDs on eng or userdebug builds.\n");
Yao Chen729093d2017-10-16 10:33:26 -0700746 }
Bookatzd2386572018-12-14 15:53:14 -0800747 name.assign(args[2].c_str(), args[2].size());
Yao Chen729093d2017-10-16 10:33:26 -0700748 }
749 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800750 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800751 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000752 includeCurrentBucket, eraseData, ADB_DUMP,
753 NO_TIME_CONSTRAINTS,
754 &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800755 if (proto) {
756 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700757 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800758 }
759 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700760 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800761 }
Yao Chen729093d2017-10-16 10:33:26 -0700762 return android::OK;
763 } else {
764 // If arg parsing failed, print the help text and return an error.
765 print_cmd_help(out);
766 return UNKNOWN_ERROR;
767 }
768 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700769 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700770 return UNKNOWN_ERROR;
771 }
772}
773
Yao Chena80e5c02018-09-04 13:55:29 -0700774status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700775 int argCount = args.size();
776 bool proto = false;
777 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
778 proto = true;
779 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800780 }
Yao Chenb3561512017-11-21 18:07:17 -0800781 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700782 if (proto) {
783 vector<uint8_t> data;
784 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
785 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700786 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700787 }
788
789 } else {
790 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
791 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700792 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700793 mProcessor->GetMetricsSize(key));
794 }
795 statsdStats.dumpStats(out);
796 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800797 return NO_ERROR;
798}
799
Yao Chena80e5c02018-09-04 13:55:29 -0700800status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800801 if (args.size() > 1) {
802 string pkg;
803 pkg.assign(args[1].c_str(), args[1].size());
804 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700805 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800806 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700807 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800808 }
Yao Chena80e5c02018-09-04 13:55:29 -0700809 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800810 } else {
811 mUidMap->printUidMap(out);
812 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700813 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700814}
815
Yao Chena80e5c02018-09-04 13:55:29 -0700816status_t StatsService::cmd_write_data_to_disk(int out) {
817 dprintf(out, "Writing data to disk\n");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000818 mProcessor->WriteDataToDisk(ADB_DUMP, NO_TIME_CONSTRAINTS);
yro947fbce2017-11-15 22:50:23 -0800819 return NO_ERROR;
820}
821
Yao Chena80e5c02018-09-04 13:55:29 -0700822status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800823 bool good = false;
824 int32_t uid;
825 int32_t label;
826 int32_t state;
827 const int argCount = args.size();
828 if (argCount == 3) {
829 // Automatically pick the UID
830 uid = IPCThreadState::self()->getCallingUid();
831 label = atoi(args[1].c_str());
832 state = atoi(args[2].c_str());
833 good = true;
834 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800835 good = getUidFromArgs(args, 1, uid);
836 if (!good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700837 dprintf(out,
Bookatzd2386572018-12-14 15:53:14 -0800838 "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
839 "done for other UIDs on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800840 }
Bookatzd2386572018-12-14 15:53:14 -0800841 label = atoi(args[2].c_str());
842 state = atoi(args[3].c_str());
Bookatzb223c4e2018-02-01 15:35:04 -0800843 }
844 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700845 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
David Chen0b5c90c2018-01-25 16:51:49 -0800846 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800847 } else {
848 print_cmd_help(out);
849 return UNKNOWN_ERROR;
850 }
851 return NO_ERROR;
852}
853
Tej Singh53f9dee2019-04-30 17:45:54 -0700854status_t StatsService::cmd_log_binary_push(int out, const Vector<String8>& args) {
855 // Security checks are done in the sendBinaryPushStateChanged atom.
856 const int argCount = args.size();
857 if (argCount != 7 && argCount != 8) {
858 dprintf(out, "Incorrect number of argument supplied\n");
859 return UNKNOWN_ERROR;
860 }
861 android::String16 trainName = android::String16(args[1].c_str());
862 int64_t trainVersion = strtoll(args[2].c_str(), nullptr, 10);
863 int options = 0;
864 if (args[3] == "1") {
Jeffrey Huang161c0752019-12-11 14:47:32 -0800865 options = options | IStatsd::FLAG_REQUIRE_STAGING;
Tej Singh53f9dee2019-04-30 17:45:54 -0700866 }
867 if (args[4] == "1") {
Jeffrey Huang161c0752019-12-11 14:47:32 -0800868 options = options | IStatsd::FLAG_ROLLBACK_ENABLED;
Tej Singh53f9dee2019-04-30 17:45:54 -0700869 }
870 if (args[5] == "1") {
Jeffrey Huang161c0752019-12-11 14:47:32 -0800871 options = options | IStatsd::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
Tej Singh53f9dee2019-04-30 17:45:54 -0700872 }
873 int32_t state = atoi(args[6].c_str());
874 vector<int64_t> experimentIds;
875 if (argCount == 8) {
876 vector<string> experimentIdsString = android::base::Split(string(args[7].c_str()), ",");
877 for (string experimentIdString : experimentIdsString) {
878 int64_t experimentId = strtoll(experimentIdString.c_str(), nullptr, 10);
879 experimentIds.push_back(experimentId);
880 }
881 }
882 dprintf(out, "Logging BinaryPushStateChanged\n");
883 sendBinaryPushStateChangedAtom(trainName, trainVersion, options, state, experimentIds);
884 return NO_ERROR;
885}
886
Yao Chena80e5c02018-09-04 13:55:29 -0700887status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700888 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700889 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800890 if (mPullerManager->Pull(s, &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700891 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700892 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700893 }
Yao Chena80e5c02018-09-04 13:55:29 -0700894 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700895 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700896 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700897 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700898}
899
Yao Chena80e5c02018-09-04 13:55:29 -0700900status_t StatsService::cmd_remove_all_configs(int out) {
901 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800902 VLOG("StatsService::cmd_remove_all_configs was called");
903 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800904 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800905 return NO_ERROR;
906}
907
Yao Chena80e5c02018-09-04 13:55:29 -0700908status_t StatsService::cmd_dump_memory_info(int out) {
909 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800910 return NO_ERROR;
911}
912
Yao Chena80e5c02018-09-04 13:55:29 -0700913status_t StatsService::cmd_clear_puller_cache(int out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800914 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800915 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
916 ipc->getCallingPid(), ipc->getCallingUid());
Chenjie Yufa22d652018-02-05 14:37:48 -0800917 if (checkCallingPermission(String16(kPermissionDump))) {
Chenjie Yue2219202018-06-08 10:07:51 -0700918 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700919 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800920 return NO_ERROR;
921 } else {
922 return PERMISSION_DENIED;
923 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800924}
925
Yao Chena80e5c02018-09-04 13:55:29 -0700926status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Yao Chen876889c2018-05-02 11:16:16 -0700927 IPCThreadState* ipc = IPCThreadState::self();
928 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", ipc->getCallingPid(),
929 ipc->getCallingUid());
930 if (checkCallingPermission(String16(kPermissionDump))) {
931 bool enabled = true;
932 if (args.size() >= 2) {
933 enabled = atoi(args[1].c_str()) != 0;
934 }
935 mProcessor->setPrintLogs(enabled);
936 return NO_ERROR;
937 } else {
938 return PERMISSION_DENIED;
939 }
940}
941
Bookatzd2386572018-12-14 15:53:14 -0800942bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800943 return getUidFromString(args[uidArgIndex].c_str(), uid);
944}
945
946bool StatsService::getUidFromString(const char* s, int32_t& uid) {
Bookatzd2386572018-12-14 15:53:14 -0800947 if (*s == '\0') {
948 return false;
949 }
950 char* endc = NULL;
951 int64_t longUid = strtol(s, &endc, 0);
952 if (*endc != '\0') {
953 return false;
954 }
955 int32_t goodUid = static_cast<int32_t>(longUid);
956 if (longUid < 0 || static_cast<uint64_t>(longUid) != static_cast<uid_t>(goodUid)) {
957 return false; // It was not of uid_t type.
958 }
959 uid = goodUid;
960
961 int32_t callingUid = IPCThreadState::self()->getCallingUid();
962 return mEngBuild // UserDebug/EngBuild are allowed to impersonate uids.
963 || (callingUid == goodUid) // Anyone can 'impersonate' themselves.
964 || (callingUid == AID_ROOT && goodUid == AID_SHELL); // ROOT can impersonate SHELL.
965}
966
Max Dashouk11e0d402019-05-16 16:58:07 -0700967Status StatsService::informAllUidData(const ParcelFileDescriptor& fd) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600968 ENFORCE_UID(AID_SYSTEM);
Max Dashouk11e0d402019-05-16 16:58:07 -0700969 // Read stream into buffer.
970 string buffer;
971 if (!android::base::ReadFdToString(fd.get(), &buffer)) {
972 return exception(Status::EX_ILLEGAL_ARGUMENT, "Failed to read all data from the pipe.");
973 }
Jeff Sharkey6b649252018-04-16 09:50:22 -0600974
Max Dashouk11e0d402019-05-16 16:58:07 -0700975 // Parse buffer.
976 UidData uidData;
977 if (!uidData.ParseFromString(buffer)) {
978 return exception(Status::EX_ILLEGAL_ARGUMENT, "Error parsing proto stream for UidData.");
979 }
David Chende701692017-10-05 13:16:02 -0700980
Max Dashouk11e0d402019-05-16 16:58:07 -0700981 vector<String16> versionStrings;
982 vector<String16> installers;
983 vector<String16> packageNames;
984 vector<int32_t> uids;
985 vector<int64_t> versions;
986
987 const auto numEntries = uidData.app_info_size();
988 versionStrings.reserve(numEntries);
989 installers.reserve(numEntries);
990 packageNames.reserve(numEntries);
991 uids.reserve(numEntries);
992 versions.reserve(numEntries);
993
994 for (const auto& appInfo: uidData.app_info()) {
995 packageNames.emplace_back(String16(appInfo.package_name().c_str()));
996 uids.push_back(appInfo.uid());
997 versions.push_back(appInfo.version());
998 versionStrings.emplace_back(String16(appInfo.version_string().c_str()));
999 installers.emplace_back(String16(appInfo.installer().c_str()));
1000 }
1001
1002 mUidMap->updateMap(getElapsedRealtimeNs(),
1003 uids,
1004 versions,
1005 versionStrings,
1006 packageNames,
1007 installers);
1008
1009 VLOG("StatsService::informAllUidData UidData proto parsed successfully.");
David Chende701692017-10-05 13:16:02 -07001010 return Status::ok();
1011}
1012
dwchen730403e2018-10-29 11:41:56 -07001013Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version,
1014 const String16& version_string, const String16& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001015 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -07001016
Jeff Sharkey6b649252018-04-16 09:50:22 -06001017 VLOG("StatsService::informOnePackage was called");
dwchen730403e2018-10-29 11:41:56 -07001018 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version, version_string, installer);
David Chende701692017-10-05 13:16:02 -07001019 return Status::ok();
1020}
1021
1022Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001023 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -07001024
Jeff Sharkey6b649252018-04-16 09:50:22 -06001025 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -07001026 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -08001027 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -07001028 return Status::ok();
1029}
1030
Yao Chenef99c4f2017-09-22 16:26:54 -07001031Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001032 ENFORCE_UID(AID_SYSTEM);
1033
yro74fed972017-11-27 14:42:42 -08001034 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -07001035 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -08001036 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
1037 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
1038 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -08001039 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -08001040 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -08001041 } else {
1042 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
1043 }
Bookatz1b0b1142017-09-08 11:58:42 -07001044 return Status::ok();
1045}
1046
Yangster-mac932ecec2018-02-01 10:23:52 -08001047Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001048 ENFORCE_UID(AID_SYSTEM);
1049
Yangster-mac932ecec2018-02-01 10:23:52 -08001050 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -07001051 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -08001052 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
1053 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
1054 if (alarmSet.size() > 0) {
1055 VLOG("Found periodic alarm fired.");
1056 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
1057 } else {
1058 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
1059 }
1060 return Status::ok();
1061}
1062
Yao Chenef99c4f2017-09-22 16:26:54 -07001063Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001064 ENFORCE_UID(AID_SYSTEM);
1065
yro74fed972017-11-27 14:42:42 -08001066 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -07001067 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -08001068 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -07001069 return Status::ok();
1070}
1071
Yao Chenef99c4f2017-09-22 16:26:54 -07001072Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001073 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001074
1075 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -08001076 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -07001077 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001078 return Status::ok();
1079}
1080
Yangster-mac892f3d32018-05-02 14:16:48 -07001081Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001082 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -07001083 VLOG("StatsService::informDeviceShutdown");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001084 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001085 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
yro947fbce2017-11-15 22:50:23 -08001086 return Status::ok();
1087}
1088
Yao Chenef99c4f2017-09-22 16:26:54 -07001089void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -07001090 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1091 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -08001092 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -07001093 statsCompanion->statsdReady();
1094 } else {
yro74fed972017-11-27 14:42:42 -08001095 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -07001096 }
1097}
1098
Yao Chenef99c4f2017-09-22 16:26:54 -07001099Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001100 ENFORCE_UID(AID_SYSTEM);
1101
yro74fed972017-11-27 14:42:42 -08001102 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -07001103 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1104 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -07001105 return Status::fromExceptionCode(
1106 Status::EX_NULL_POINTER,
1107 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -07001108 }
yro74fed972017-11-27 14:42:42 -08001109 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001110 IInterface::asBinder(statsCompanion)->linkToDeath(this);
Chenjie Yue2219202018-06-08 10:07:51 -07001111 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -08001112 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
1113 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -08001114 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -07001115 return Status::ok();
1116}
1117
Joe Onorato9fc9edf2017-10-15 20:08:52 -07001118void StatsService::Startup() {
1119 mConfigManager->Startup();
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001120 mProcessor->LoadActiveConfigsFromDisk();
Bookatz906a35c2017-09-20 15:26:44 -07001121}
1122
Yangster-mac97e7d202018-10-09 11:05:39 -07001123void StatsService::Terminate() {
1124 ALOGI("StatsService::Terminating");
1125 if (mProcessor != nullptr) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001126 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001127 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
Yangster-mac97e7d202018-10-09 11:05:39 -07001128 }
1129}
1130
Yao Chen0f861862019-03-27 11:51:15 -07001131// Test only interface!!!
Yao Chen3ff3a492018-08-06 16:17:37 -07001132void StatsService::OnLogEvent(LogEvent* event) {
1133 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -07001134 if (mShellSubscriber != nullptr) {
1135 mShellSubscriber->onLogEvent(*event);
1136 }
Bookatz906a35c2017-09-20 15:26:44 -07001137}
1138
Jeff Sharkey6b649252018-04-16 09:50:22 -06001139Status StatsService::getData(int64_t key, const String16& packageName, vector<uint8_t>* output) {
1140 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1141
David Chenadaf8b32017-11-03 15:42:08 -07001142 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -08001143 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001144 ConfigKey configKey(ipc->getCallingUid(), key);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001145 // The dump latency does not matter here since we do not include the current bucket, we do not
1146 // need to pull any new data anyhow.
David Chen56ae0d92018-05-11 16:00:22 -07001147 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001148 true /* erase_data */, GET_DATA_CALLED, FAST, output);
Bookatz4f716292018-04-10 17:15:12 -07001149 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001150}
1151
Jeff Sharkey6b649252018-04-16 09:50:22 -06001152Status StatsService::getMetadata(const String16& packageName, vector<uint8_t>* output) {
1153 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1154
David Chen2e8f3802017-11-22 10:56:48 -08001155 IPCThreadState* ipc = IPCThreadState::self();
1156 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
1157 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001158 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
1159 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -08001160}
1161
Jeff Sharkey6b649252018-04-16 09:50:22 -06001162Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
1163 const String16& packageName) {
1164 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1165
David Chenadaf8b32017-11-03 15:42:08 -07001166 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -07001167 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -08001168 return Status::ok();
1169 } else {
Bookatz4f716292018-04-10 17:15:12 -07001170 ALOGE("Could not parse malformatted StatsdConfig");
1171 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
1172 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -08001173 }
1174}
1175
David Chen9fdd4032018-03-20 14:38:56 -07001176bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
1177 ConfigKey configKey(uid, key);
1178 StatsdConfig cfg;
1179 if (config.size() > 0) { // If the config is empty, skip parsing.
1180 if (!cfg.ParseFromArray(&config[0], config.size())) {
1181 return false;
1182 }
1183 }
1184 mConfigManager->UpdateConfig(configKey, cfg);
1185 return true;
1186}
1187
Jeff Sharkey6b649252018-04-16 09:50:22 -06001188Status StatsService::removeDataFetchOperation(int64_t key, const String16& packageName) {
1189 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1190
Bookatz4f716292018-04-10 17:15:12 -07001191 IPCThreadState* ipc = IPCThreadState::self();
1192 ConfigKey configKey(ipc->getCallingUid(), key);
1193 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,
1198 const sp<android::IBinder>& intentSender,
1199 const String16& packageName) {
1200 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1201
Bookatz4f716292018-04-10 17:15:12 -07001202 IPCThreadState* ipc = IPCThreadState::self();
1203 ConfigKey configKey(ipc->getCallingUid(), key);
1204 mConfigManager->SetConfigReceiver(configKey, intentSender);
David Chen48944902018-05-03 10:29:11 -07001205 if (StorageManager::hasConfigMetricsReport(configKey)) {
1206 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
1207 configKey.ToString().c_str());
1208 mProcessor->noteOnDiskData(configKey);
1209 }
Bookatz4f716292018-04-10 17:15:12 -07001210 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001211}
1212
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001213Status StatsService::setActiveConfigsChangedOperation(const sp<android::IBinder>& intentSender,
1214 const String16& packageName,
1215 vector<int64_t>* output) {
1216 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1217
1218 IPCThreadState* ipc = IPCThreadState::self();
Tej Singh6ede28b2019-01-29 17:06:54 -08001219 int uid = ipc->getCallingUid();
1220 mConfigManager->SetActiveConfigsChangedReceiver(uid, intentSender);
1221 if (output != nullptr) {
1222 mProcessor->GetActiveConfigs(uid, *output);
1223 } else {
1224 ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
1225 }
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001226 return Status::ok();
1227}
1228
1229Status StatsService::removeActiveConfigsChangedOperation(const String16& packageName) {
1230 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1231
1232 IPCThreadState* ipc = IPCThreadState::self();
1233 mConfigManager->RemoveActiveConfigsChangedReceiver(ipc->getCallingUid());
1234 return Status::ok();
1235}
1236
Jeff Sharkey6b649252018-04-16 09:50:22 -06001237Status StatsService::removeConfiguration(int64_t key, const String16& packageName) {
1238 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1239
Bookatz4f716292018-04-10 17:15:12 -07001240 IPCThreadState* ipc = IPCThreadState::self();
1241 ConfigKey configKey(ipc->getCallingUid(), key);
1242 mConfigManager->RemoveConfig(configKey);
1243 SubscriberReporter::getInstance().removeConfig(configKey);
1244 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001245}
1246
Bookatzc6977972018-01-16 16:55:05 -08001247Status StatsService::setBroadcastSubscriber(int64_t configId,
1248 int64_t subscriberId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001249 const sp<android::IBinder>& intentSender,
1250 const String16& packageName) {
1251 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1252
Bookatzc6977972018-01-16 16:55:05 -08001253 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001254 IPCThreadState* ipc = IPCThreadState::self();
1255 ConfigKey configKey(ipc->getCallingUid(), configId);
1256 SubscriberReporter::getInstance()
1257 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
1258 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001259}
1260
1261Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001262 int64_t subscriberId,
1263 const String16& packageName) {
1264 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1265
Bookatzc6977972018-01-16 16:55:05 -08001266 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001267 IPCThreadState* ipc = IPCThreadState::self();
1268 ConfigKey configKey(ipc->getCallingUid(), configId);
1269 SubscriberReporter::getInstance()
1270 .unsetBroadcastSubscriber(configKey, subscriberId);
1271 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001272}
1273
yrobe6d7f92018-05-04 13:02:53 -07001274Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
1275 // Permission check not necessary as it's meant for applications to write to
1276 // statsd.
1277 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
Jeff Sharkey6bd21572019-11-15 20:45:33 -07001278 (int32_t) IPCThreadState::self()->getCallingUid(), label,
yrobe6d7f92018-05-04 13:02:53 -07001279 state);
1280 return Status::ok();
1281}
1282
Tej Singha0c89dd2019-01-25 16:39:18 -08001283Status StatsService::registerPullerCallback(int32_t atomTag,
1284 const sp<android::os::IStatsPullerCallback>& pullerCallback,
1285 const String16& packageName) {
1286 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1287
1288 VLOG("StatsService::registerPullerCallback called.");
1289 mPullerManager->RegisterPullerCallback(atomTag, pullerCallback);
1290 return Status::ok();
1291}
1292
Tej Singh59184292019-10-11 11:07:06 -07001293Status StatsService::registerPullAtomCallback(int32_t uid, int32_t atomTag, int64_t coolDownNs,
1294 int64_t timeoutNs, const std::vector<int32_t>& additiveFields,
1295 const sp<android::os::IPullAtomCallback>& pullerCallback) {
Tej Singh6a5c9432019-10-11 11:07:06 -07001296 ENFORCE_UID(AID_SYSTEM);
1297
Tej Singhb7802512019-12-04 17:57:04 -08001298 VLOG("StatsService::registerPullAtomCallback called.");
1299 mPullerManager->RegisterPullAtomCallback(uid, atomTag, coolDownNs, timeoutNs, additiveFields,
1300 pullerCallback);
1301 return Status::ok();
1302}
1303
1304Status StatsService::registerNativePullAtomCallback(int32_t atomTag, int64_t coolDownNs,
1305 int64_t timeoutNs, const std::vector<int32_t>& additiveFields,
1306 const sp<android::os::IPullAtomCallback>& pullerCallback) {
1307
1308 VLOG("StatsService::registerNativePullAtomCallback called.");
1309 int32_t uid = IPCThreadState::self()->getCallingUid();
Tej Singh6a5c9432019-10-11 11:07:06 -07001310 mPullerManager->RegisterPullAtomCallback(uid, atomTag, coolDownNs, timeoutNs, additiveFields,
1311 pullerCallback);
Tej Singh59184292019-10-11 11:07:06 -07001312 return Status::ok();
1313}
1314
Tej Singha0c89dd2019-01-25 16:39:18 -08001315Status StatsService::unregisterPullerCallback(int32_t atomTag, const String16& packageName) {
1316 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1317
1318 VLOG("StatsService::unregisterPullerCallback called.");
1319 mPullerManager->UnregisterPullerCallback(atomTag);
1320 return Status::ok();
1321}
1322
Tej Singhfa1c1372019-12-05 20:36:54 -08001323Status StatsService::unregisterPullAtomCallback(int32_t uid, int32_t atomTag) {
1324 ENFORCE_UID(AID_SYSTEM);
1325 VLOG("StatsService::unregisterPullAtomCallback called.");
1326 mPullerManager->UnregisterPullAtomCallback(uid, atomTag);
1327 return Status::ok();
1328}
1329
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001330Status StatsService::sendBinaryPushStateChangedAtom(const android::String16& trainNameIn,
1331 const int64_t trainVersionCodeIn,
1332 const int options,
1333 const int32_t state,
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001334 const std::vector<int64_t>& experimentIdsIn) {
Tej Singh53f9dee2019-04-30 17:45:54 -07001335 // Note: We skip the usage stats op check here since we do not have a package name.
1336 // This is ok since we are overloading the usage_stats permission.
1337 // This method only sends data, it does not receive it.
1338 pid_t pid = IPCThreadState::self()->getCallingPid();
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001339 uid_t uid = IPCThreadState::self()->getCallingUid();
Tej Singh73f8e9b2019-05-19 16:52:38 -07001340 // Root, system, and shell always have access
Tej Singh53f9dee2019-04-30 17:45:54 -07001341 if (uid != AID_ROOT && uid != AID_SYSTEM && uid != AID_SHELL) {
1342 // Caller must be granted these permissions
1343 if (!checkCallingPermission(String16(kPermissionDump))) {
1344 return exception(binder::Status::EX_SECURITY,
1345 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1346 kPermissionDump));
1347 }
1348 if (!checkCallingPermission(String16(kPermissionUsage))) {
1349 return exception(binder::Status::EX_SECURITY,
1350 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1351 kPermissionUsage));
1352 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001353 }
1354
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001355 bool readTrainInfoSuccess = false;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001356 InstallTrainInfo trainInfoOnDisk;
1357 readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfoOnDisk);
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001358
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001359 bool resetExperimentIds = false;
1360 int64_t trainVersionCode = trainVersionCodeIn;
1361 std::string trainNameUtf8 = std::string(String8(trainNameIn).string());
1362 if (readTrainInfoSuccess) {
1363 // Keep the old train version if we received an empty version.
1364 if (trainVersionCodeIn == -1) {
1365 trainVersionCode = trainInfoOnDisk.trainVersionCode;
1366 } else if (trainVersionCodeIn != trainInfoOnDisk.trainVersionCode) {
1367 // Reset experiment ids if we receive a new non-empty train version.
1368 resetExperimentIds = true;
1369 }
1370
1371 // Keep the old train name if we received an empty train name.
1372 if (trainNameUtf8.size() == 0) {
1373 trainNameUtf8 = trainInfoOnDisk.trainName;
1374 } else if (trainNameUtf8 != trainInfoOnDisk.trainName) {
1375 // Reset experiment ids if we received a new valid train name.
1376 resetExperimentIds = true;
1377 }
1378
1379 // Reset if we received a different experiment id.
1380 if (!experimentIdsIn.empty() &&
1381 (trainInfoOnDisk.experimentIds.empty() ||
1382 experimentIdsIn[0] != trainInfoOnDisk.experimentIds[0])) {
1383 resetExperimentIds = true;
1384 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001385 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001386
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001387 // Find the right experiment IDs
1388 std::vector<int64_t> experimentIds;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001389 if (resetExperimentIds || !readTrainInfoSuccess) {
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001390 experimentIds = experimentIdsIn;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001391 } else {
1392 experimentIds = trainInfoOnDisk.experimentIds;
1393 }
1394
1395 if (!experimentIds.empty()) {
1396 int64_t firstId = experimentIds[0];
1397 switch (state) {
1398 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALL_SUCCESS:
1399 experimentIds.push_back(firstId + 1);
1400 break;
1401 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_INITIATED:
1402 experimentIds.push_back(firstId + 2);
1403 break;
1404 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_SUCCESS:
1405 experimentIds.push_back(firstId + 3);
1406 break;
1407 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001408 }
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001409
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001410 // Flatten the experiment IDs to proto
1411 vector<uint8_t> experimentIdsProtoBuffer;
1412 writeExperimentIdsToProto(experimentIds, &experimentIdsProtoBuffer);
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001413 StorageManager::writeTrainInfo(trainVersionCode, trainNameUtf8, state, experimentIds);
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001414
1415 userid_t userId = multiuser_get_user_id(uid);
Jeffrey Huang161c0752019-12-11 14:47:32 -08001416 bool requiresStaging = options & IStatsd::FLAG_REQUIRE_STAGING;
1417 bool rollbackEnabled = options & IStatsd::FLAG_ROLLBACK_ENABLED;
1418 bool requiresLowLatencyMonitor = options & IStatsd::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001419 LogEvent event(trainNameUtf8, trainVersionCode, requiresStaging, rollbackEnabled,
1420 requiresLowLatencyMonitor, state, experimentIdsProtoBuffer, userId);
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001421 mProcessor->OnLogEvent(&event);
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001422 return Status::ok();
1423}
1424
Tej Singh73f8e9b2019-05-19 16:52:38 -07001425Status StatsService::sendWatchdogRollbackOccurredAtom(const int32_t rollbackTypeIn,
1426 const android::String16& packageNameIn,
Gavin Corkerydd1daba2019-11-27 19:11:13 +00001427 const int64_t packageVersionCodeIn,
1428 const int32_t rollbackReasonIn,
1429 const android::String16&
1430 failingPackageNameIn) {
Tej Singh73f8e9b2019-05-19 16:52:38 -07001431 // Note: We skip the usage stats op check here since we do not have a package name.
1432 // This is ok since we are overloading the usage_stats permission.
1433 // This method only sends data, it does not receive it.
1434 pid_t pid = IPCThreadState::self()->getCallingPid();
1435 uid_t uid = IPCThreadState::self()->getCallingUid();
1436 // Root, system, and shell always have access
1437 if (uid != AID_ROOT && uid != AID_SYSTEM && uid != AID_SHELL) {
1438 // Caller must be granted these permissions
1439 if (!checkCallingPermission(String16(kPermissionDump))) {
1440 return exception(binder::Status::EX_SECURITY,
1441 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1442 kPermissionDump));
1443 }
1444 if (!checkCallingPermission(String16(kPermissionUsage))) {
1445 return exception(binder::Status::EX_SECURITY,
1446 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1447 kPermissionUsage));
1448 }
1449 }
1450
1451 android::util::stats_write(android::util::WATCHDOG_ROLLBACK_OCCURRED,
Gavin Corkerydd1daba2019-11-27 19:11:13 +00001452 rollbackTypeIn, String8(packageNameIn).string(), packageVersionCodeIn,
1453 rollbackReasonIn, String8(failingPackageNameIn).string());
Tej Singh73f8e9b2019-05-19 16:52:38 -07001454
1455 // Fast return to save disk read.
1456 if (rollbackTypeIn != android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS
1457 && rollbackTypeIn !=
1458 android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE) {
1459 return Status::ok();
1460 }
1461
1462 bool readTrainInfoSuccess = false;
1463 InstallTrainInfo trainInfoOnDisk;
1464 readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfoOnDisk);
1465
1466 if (!readTrainInfoSuccess) {
1467 return Status::ok();
1468 }
1469 std::vector<int64_t> experimentIds = trainInfoOnDisk.experimentIds;
1470 if (experimentIds.empty()) {
1471 return Status::ok();
1472 }
1473 switch (rollbackTypeIn) {
1474 case android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_INITIATE:
1475 experimentIds.push_back(experimentIds[0] + 4);
1476 break;
1477 case android::util::WATCHDOG_ROLLBACK_OCCURRED__ROLLBACK_TYPE__ROLLBACK_SUCCESS:
1478 experimentIds.push_back(experimentIds[0] + 5);
1479 break;
1480 }
1481 StorageManager::writeTrainInfo(trainInfoOnDisk.trainVersionCode, trainInfoOnDisk.trainName,
1482 trainInfoOnDisk.status, experimentIds);
1483 return Status::ok();
1484}
1485
1486
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001487Status StatsService::getRegisteredExperimentIds(std::vector<int64_t>* experimentIdsOut) {
1488 uid_t uid = IPCThreadState::self()->getCallingUid();
1489
1490 // Caller must be granted these permissions
1491 if (!checkCallingPermission(String16(kPermissionDump))) {
1492 return exception(binder::Status::EX_SECURITY,
1493 StringPrintf("UID %d lacks permission %s", uid, kPermissionDump));
1494 }
1495 if (!checkCallingPermission(String16(kPermissionUsage))) {
1496 return exception(binder::Status::EX_SECURITY,
1497 StringPrintf("UID %d lacks permission %s", uid, kPermissionUsage));
1498 }
1499 // TODO: add verifier permission
1500
1501 // Read the latest train info
1502 InstallTrainInfo trainInfo;
1503 if (!StorageManager::readTrainInfo(trainInfo)) {
1504 // No train info means no experiment IDs, return an empty list
1505 experimentIdsOut->clear();
1506 return Status::ok();
1507 }
1508
1509 // Copy the experiment IDs to the out vector
1510 experimentIdsOut->assign(trainInfo.experimentIds.begin(), trainInfo.experimentIds.end());
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001511 return Status::ok();
1512}
1513
Howard Roa46b6582018-09-18 16:45:02 -07001514hardware::Return<void> StatsService::reportSpeakerImpedance(
1515 const SpeakerImpedance& speakerImpedance) {
Tej Singh8928ed72019-02-22 19:06:22 -08001516 android::util::stats_write(android::util::SPEAKER_IMPEDANCE_REPORTED,
1517 speakerImpedance.speakerLocation, speakerImpedance.milliOhms);
Howard Roa46b6582018-09-18 16:45:02 -07001518
1519 return hardware::Void();
1520}
1521
1522hardware::Return<void> StatsService::reportHardwareFailed(const HardwareFailed& hardwareFailed) {
Tej Singh8928ed72019-02-22 19:06:22 -08001523 android::util::stats_write(android::util::HARDWARE_FAILED, int32_t(hardwareFailed.hardwareType),
1524 hardwareFailed.hardwareLocation, int32_t(hardwareFailed.errorCode));
Howard Roa46b6582018-09-18 16:45:02 -07001525
1526 return hardware::Void();
1527}
1528
1529hardware::Return<void> StatsService::reportPhysicalDropDetected(
1530 const PhysicalDropDetected& physicalDropDetected) {
Tej Singh8928ed72019-02-22 19:06:22 -08001531 android::util::stats_write(android::util::PHYSICAL_DROP_DETECTED,
1532 int32_t(physicalDropDetected.confidencePctg), physicalDropDetected.accelPeak,
1533 physicalDropDetected.freefallDuration);
Howard Roa46b6582018-09-18 16:45:02 -07001534
1535 return hardware::Void();
1536}
1537
1538hardware::Return<void> StatsService::reportChargeCycles(const ChargeCycles& chargeCycles) {
Tej Singh8928ed72019-02-22 19:06:22 -08001539 std::vector<int32_t> buckets = chargeCycles.cycleBucket;
1540 int initialSize = buckets.size();
1541 for (int i = 0; i < 10 - initialSize; i++) {
1542 buckets.push_back(-1); // Push -1 for buckets that do not exist.
1543 }
1544 android::util::stats_write(android::util::CHARGE_CYCLES_REPORTED, buckets[0], buckets[1],
1545 buckets[2], buckets[3], buckets[4], buckets[5], buckets[6], buckets[7], buckets[8],
1546 buckets[9]);
Howard Roa46b6582018-09-18 16:45:02 -07001547
1548 return hardware::Void();
1549}
1550
1551hardware::Return<void> StatsService::reportBatteryHealthSnapshot(
1552 const BatteryHealthSnapshotArgs& batteryHealthSnapshotArgs) {
Tej Singh8928ed72019-02-22 19:06:22 -08001553 android::util::stats_write(android::util::BATTERY_HEALTH_SNAPSHOT,
1554 int32_t(batteryHealthSnapshotArgs.type), batteryHealthSnapshotArgs.temperatureDeciC,
1555 batteryHealthSnapshotArgs.voltageMicroV, batteryHealthSnapshotArgs.currentMicroA,
1556 batteryHealthSnapshotArgs.openCircuitVoltageMicroV,
1557 batteryHealthSnapshotArgs.resistanceMicroOhm, batteryHealthSnapshotArgs.levelPercent);
Howard Roa46b6582018-09-18 16:45:02 -07001558
1559 return hardware::Void();
1560}
1561
1562hardware::Return<void> StatsService::reportSlowIo(const SlowIo& slowIo) {
Tej Singh8928ed72019-02-22 19:06:22 -08001563 android::util::stats_write(android::util::SLOW_IO, int32_t(slowIo.operation), slowIo.count);
Howard Roa46b6582018-09-18 16:45:02 -07001564
1565 return hardware::Void();
1566}
1567
1568hardware::Return<void> StatsService::reportBatteryCausedShutdown(
1569 const BatteryCausedShutdown& batteryCausedShutdown) {
Tej Singh8928ed72019-02-22 19:06:22 -08001570 android::util::stats_write(android::util::BATTERY_CAUSED_SHUTDOWN,
1571 batteryCausedShutdown.voltageMicroV);
Howard Roa46b6582018-09-18 16:45:02 -07001572
1573 return hardware::Void();
1574}
1575
Maggie Whitefc1aa592018-11-28 21:55:23 -08001576hardware::Return<void> StatsService::reportUsbPortOverheatEvent(
1577 const UsbPortOverheatEvent& usbPortOverheatEvent) {
Tej Singh8928ed72019-02-22 19:06:22 -08001578 android::util::stats_write(android::util::USB_PORT_OVERHEAT_EVENT_REPORTED,
1579 usbPortOverheatEvent.plugTemperatureDeciC, usbPortOverheatEvent.maxTemperatureDeciC,
1580 usbPortOverheatEvent.timeToOverheat, usbPortOverheatEvent.timeToHysteresis,
1581 usbPortOverheatEvent.timeToInactive);
Maggie Whitefc1aa592018-11-28 21:55:23 -08001582
1583 return hardware::Void();
1584}
1585
Carter Hsub8fd1e92019-01-11 15:24:45 +08001586hardware::Return<void> StatsService::reportSpeechDspStat(
1587 const SpeechDspStat& speechDspStat) {
Tej Singh8928ed72019-02-22 19:06:22 -08001588 android::util::stats_write(android::util::SPEECH_DSP_STAT_REPORTED,
1589 speechDspStat.totalUptimeMillis, speechDspStat.totalDowntimeMillis,
1590 speechDspStat.totalCrashCount, speechDspStat.totalRecoverCount);
Carter Hsub8fd1e92019-01-11 15:24:45 +08001591
1592 return hardware::Void();
1593}
1594
Maggie White58174da2019-01-18 15:23:35 -08001595hardware::Return<void> StatsService::reportVendorAtom(const VendorAtom& vendorAtom) {
1596 std::string reverseDomainName = (std::string) vendorAtom.reverseDomainName;
1597 if (vendorAtom.atomId < 100000 || vendorAtom.atomId >= 200000) {
1598 ALOGE("Atom ID %ld is not a valid vendor atom ID", (long) vendorAtom.atomId);
1599 return hardware::Void();
1600 }
1601 if (reverseDomainName.length() > 50) {
1602 ALOGE("Vendor atom reverse domain name %s is too long.", reverseDomainName.c_str());
1603 return hardware::Void();
1604 }
1605 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), vendorAtom);
1606 mProcessor->OnLogEvent(&event);
1607
1608 return hardware::Void();
1609}
1610
David Chen1d7b0cd2017-11-15 14:20:04 -08001611void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001612 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001613 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1614 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001615 ALOGW("Reset statsd upon system server restarts.");
Tej Singhf53d4452019-05-09 18:17:59 -07001616 int64_t systemServerRestartNs = getElapsedRealtimeNs();
1617 ProtoOutputStream proto;
1618 mProcessor->WriteActiveConfigsToProtoOutputStream(systemServerRestartNs,
1619 STATSCOMPANION_DIED, &proto);
1620
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001621 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED, FAST);
Yangster-mac892f3d32018-05-02 14:16:48 -07001622 mProcessor->resetConfigs();
Tej Singhf53d4452019-05-09 18:17:59 -07001623
1624 std::string serializedActiveConfigs;
1625 if (proto.serializeToString(&serializedActiveConfigs)) {
1626 ActiveConfigList activeConfigs;
1627 if (activeConfigs.ParseFromString(serializedActiveConfigs)) {
1628 mProcessor->SetConfigsActiveState(activeConfigs, systemServerRestartNs);
1629 }
1630 }
Yangster-mac892f3d32018-05-02 14:16:48 -07001631 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001632 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1633 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
1634 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001635 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001636}
1637
Yao Chenef99c4f2017-09-22 16:26:54 -07001638} // namespace statsd
1639} // namespace os
1640} // namespace android