blob: 8191d37bb6038dd1a8f99f9ae98c06717436fdcd [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>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070038#include <private/android_filesystem_config.h>
Bookatzb223c4e2018-02-01 15:35:04 -080039#include <statslog.h>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070040#include <stdio.h>
Yao Chen482d2722017-09-12 13:25:43 -070041#include <stdlib.h>
Joe Onorato9fc9edf2017-10-15 20:08:52 -070042#include <sys/system_properties.h>
Yao Chenef99c4f2017-09-22 16:26:54 -070043#include <unistd.h>
Yao Chena80e5c02018-09-04 13:55:29 -070044#include <utils/Looper.h>
45#include <utils/String16.h>
46#include <chrono>
Joe Onorato5dcbc6c2017-08-29 15:13:58 -070047
48using namespace android;
49
Jeff Sharkey6b649252018-04-16 09:50:22 -060050using android::base::StringPrintf;
Bookatzff71cad2018-09-20 17:17:49 -070051using android::util::FIELD_COUNT_REPEATED;
Chenjie Yu6b1667c2019-01-18 10:09:33 -080052using android::util::FIELD_TYPE_INT64;
Bookatzff71cad2018-09-20 17:17:49 -070053using android::util::FIELD_TYPE_MESSAGE;
Joe Onorato99598ee2019-02-11 15:55:13 +000054using android::util::ProtoReader;
Jeff Sharkey6b649252018-04-16 09:50:22 -060055
Bookatz906a35c2017-09-20 15:26:44 -070056namespace android {
57namespace os {
58namespace statsd {
59
David Chenadaf8b32017-11-03 15:42:08 -070060constexpr const char* kPermissionDump = "android.permission.DUMP";
Jeff Sharkey6b649252018-04-16 09:50:22 -060061constexpr const char* kPermissionUsage = "android.permission.PACKAGE_USAGE_STATS";
62
63constexpr const char* kOpUsage = "android:get_usage_stats";
64
yro03faf092017-12-12 00:17:50 -080065#define STATS_SERVICE_DIR "/data/misc/stats-service"
David Chenadaf8b32017-11-03 15:42:08 -070066
Bookatzff71cad2018-09-20 17:17:49 -070067// for StatsDataDumpProto
68const int FIELD_ID_REPORTS_LIST = 1;
69
Jeff Sharkey6b649252018-04-16 09:50:22 -060070static binder::Status ok() {
71 return binder::Status::ok();
72}
73
74static binder::Status exception(uint32_t code, const std::string& msg) {
75 ALOGE("%s (%d)", msg.c_str(), code);
76 return binder::Status::fromExceptionCode(code, String8(msg.c_str()));
77}
78
79binder::Status checkUid(uid_t expectedUid) {
80 uid_t uid = IPCThreadState::self()->getCallingUid();
81 if (uid == expectedUid || uid == AID_ROOT) {
82 return ok();
83 } else {
84 return exception(binder::Status::EX_SECURITY,
85 StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
86 }
87}
88
89binder::Status checkDumpAndUsageStats(const String16& packageName) {
90 pid_t pid = IPCThreadState::self()->getCallingPid();
91 uid_t uid = IPCThreadState::self()->getCallingUid();
92
93 // Root, system, and shell always have access
94 if (uid == AID_ROOT || uid == AID_SYSTEM || uid == AID_SHELL) {
95 return ok();
96 }
97
98 // Caller must be granted these permissions
99 if (!checkCallingPermission(String16(kPermissionDump))) {
100 return exception(binder::Status::EX_SECURITY,
101 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionDump));
102 }
103 if (!checkCallingPermission(String16(kPermissionUsage))) {
104 return exception(binder::Status::EX_SECURITY,
105 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid, kPermissionUsage));
106 }
107
108 // Caller must also have usage stats op granted
109 PermissionController pc;
110 switch (pc.noteOp(String16(kOpUsage), uid, packageName)) {
111 case PermissionController::MODE_ALLOWED:
112 case PermissionController::MODE_DEFAULT:
113 return ok();
114 default:
115 return exception(binder::Status::EX_SECURITY,
116 StringPrintf("UID %d / PID %d lacks app-op %s", uid, pid, kOpUsage));
117 }
118}
119
120#define ENFORCE_UID(uid) { \
121 binder::Status status = checkUid((uid)); \
122 if (!status.isOk()) { \
123 return status; \
124 } \
125}
126
127#define ENFORCE_DUMP_AND_USAGE_STATS(packageName) { \
128 binder::Status status = checkDumpAndUsageStats(packageName); \
129 if (!status.isOk()) { \
130 return status; \
131 } \
132}
133
Yao Chen0f861862019-03-27 11:51:15 -0700134StatsService::StatsService(const sp<Looper>& handlerLooper, shared_ptr<LogEventQueue> queue)
135 : mAnomalyAlarmMonitor(new AlarmMonitor(
136 MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
137 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
138 if (sc != nullptr) {
139 sc->setAnomalyAlarm(timeMillis);
140 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
141 }
142 },
143 [](const sp<IStatsCompanionService>& sc) {
144 if (sc != nullptr) {
145 sc->cancelAnomalyAlarm();
146 StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
147 }
148 })),
149 mPeriodicAlarmMonitor(new AlarmMonitor(
150 MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
151 [](const sp<IStatsCompanionService>& sc, int64_t timeMillis) {
152 if (sc != nullptr) {
153 sc->setAlarmForSubscriberTriggering(timeMillis);
154 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
155 }
156 },
157 [](const sp<IStatsCompanionService>& sc) {
158 if (sc != nullptr) {
159 sc->cancelAlarmForSubscriberTriggering();
160 StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
161 }
162 })),
163 mEventQueue(queue) {
Yao Chen4ce07292019-02-13 13:06:36 -0800164 mUidMap = UidMap::getInstance();
Chenjie Yue2219202018-06-08 10:07:51 -0700165 mPullerManager = new StatsPullerManager();
Chenjie Yu80f91122018-01-31 20:24:50 -0800166 StatsPuller::SetUidMap(mUidMap);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700167 mConfigManager = new ConfigManager();
Chenjie Yue2219202018-06-08 10:07:51 -0700168 mProcessor = new StatsLogProcessor(
169 mUidMap, mPullerManager, mAnomalyAlarmMonitor, mPeriodicAlarmMonitor,
Chenjie Yuc7939cb2019-02-04 17:25:45 -0800170 getElapsedRealtimeNs(),
171 [this](const ConfigKey& key) {
Chenjie Yue2219202018-06-08 10:07:51 -0700172 sp<IStatsCompanionService> sc = getStatsCompanionService();
173 auto receiver = mConfigManager->GetConfigReceiver(key);
174 if (sc == nullptr) {
175 VLOG("Could not find StatsCompanionService");
176 return false;
177 } else if (receiver == nullptr) {
178 VLOG("Statscompanion could not find a broadcast receiver for %s",
179 key.ToString().c_str());
180 return false;
181 } else {
182 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
183 return true;
184 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800185 },
186 [this](const int& uid, const vector<int64_t>& activeConfigs) {
187 auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
188 sp<IStatsCompanionService> sc = getStatsCompanionService();
189 if (sc == nullptr) {
190 VLOG("Could not access statsCompanion");
191 return false;
192 } else if (receiver == nullptr) {
193 VLOG("Could not find receiver for uid %d", uid);
194 return false;
195 } else {
196 sc->sendActiveConfigsChangedBroadcast(receiver, activeConfigs);
197 VLOG("StatsService::active configs broadcast succeeded for uid %d" , uid);
198 return true;
199 }
Chenjie Yue2219202018-06-08 10:07:51 -0700200 });
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700201
202 mConfigManager->AddListener(mProcessor);
203
204 init_system_properties();
Yao Chen0f861862019-03-27 11:51:15 -0700205
206 if (mEventQueue != nullptr) {
207 std::thread pushedEventThread([this] { readLogs(); });
208 pushedEventThread.detach();
209 }
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700210}
211
Yao Chenef99c4f2017-09-22 16:26:54 -0700212StatsService::~StatsService() {
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700213}
214
Yao Chen0f861862019-03-27 11:51:15 -0700215/* Runs on a dedicated thread to process pushed events. */
216void StatsService::readLogs() {
217 // Read forever..... long live statsd
218 while (1) {
219 // Block until an event is available.
220 auto event = mEventQueue->waitPop();
221 // Pass it to StatsLogProcess to all configs/metrics
222 // At this point, the LogEventQueue is not blocked, so that the socketListener
223 // can read events from the socket and write to buffer to avoid data drop.
224 mProcessor->OnLogEvent(event.get());
225 // The ShellSubscriber is only used by shell for local debugging.
226 if (mShellSubscriber != nullptr) {
227 mShellSubscriber->onLogEvent(*event);
228 }
229 }
230}
231
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700232void StatsService::init_system_properties() {
233 mEngBuild = false;
234 const prop_info* buildType = __system_property_find("ro.build.type");
235 if (buildType != NULL) {
236 __system_property_read_callback(buildType, init_build_type_callback, this);
237 }
David Chen0656b7a2017-09-13 15:53:39 -0700238}
239
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700240void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
241 uint32_t serial) {
Yao Chen729093d2017-10-16 10:33:26 -0700242 if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700243 reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
244 }
245}
246
247/**
248 * Implement our own because the default binder implementation isn't
249 * properly handling SHELL_COMMAND_TRANSACTION.
250 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700251status_t StatsService::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
252 uint32_t flags) {
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700253 switch (code) {
254 case SHELL_COMMAND_TRANSACTION: {
255 int in = data.readFileDescriptor();
256 int out = data.readFileDescriptor();
257 int err = data.readFileDescriptor();
258 int argc = data.readInt32();
259 Vector<String8> args;
260 for (int i = 0; i < argc && data.dataAvail() > 0; i++) {
261 args.add(String8(data.readString16()));
262 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700263 sp<IShellCallback> shellCallback = IShellCallback::asInterface(data.readStrongBinder());
264 sp<IResultReceiver> resultReceiver =
265 IResultReceiver::asInterface(data.readStrongBinder());
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700266
Yao Chena80e5c02018-09-04 13:55:29 -0700267 err = command(in, out, err, args, resultReceiver);
268 resultReceiver->send(err);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700269 return NO_ERROR;
270 }
Yao Chenef99c4f2017-09-22 16:26:54 -0700271 default: { return BnStatsManager::onTransact(code, data, reply, flags); }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700272 }
273}
274
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700275/**
Bookatzff71cad2018-09-20 17:17:49 -0700276 * Write data from statsd.
277 * Format for statsdStats: adb shell dumpsys stats --metadata [-v] [--proto]
278 * Format for data report: adb shell dumpsys stats [anything other than --metadata] [--proto]
279 * Anything ending in --proto will be in proto format.
280 * Anything without --metadata as the first argument will be report information.
281 * (bugreports call "adb shell dumpsys stats --dump-priority NORMAL -a --proto")
282 * TODO: Come up with a more robust method of enacting <serviceutils/PriorityDumper.h>.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700283 */
Yao Chenef99c4f2017-09-22 16:26:54 -0700284status_t StatsService::dump(int fd, const Vector<String16>& args) {
Tej Singhdd83d702018-04-10 17:24:50 -0700285 if (!checkCallingPermission(String16(kPermissionDump))) {
286 return PERMISSION_DENIED;
287 }
Bookatzff71cad2018-09-20 17:17:49 -0700288 int lastArg = args.size() - 1;
289 bool asProto = false;
290 if (lastArg >= 0 && !args[lastArg].compare(String16("--proto"))) { // last argument
291 asProto = true;
292 lastArg--;
Yao Chen884c8c12018-01-26 10:36:25 -0800293 }
Bookatzff71cad2018-09-20 17:17:49 -0700294 if (args.size() > 0 && !args[0].compare(String16("--metadata"))) { // first argument
295 // Request is to dump statsd stats.
296 bool verbose = false;
297 if (lastArg >= 0 && !args[lastArg].compare(String16("-v"))) {
298 verbose = true;
299 lastArg--;
300 }
301 dumpStatsdStats(fd, verbose, asProto);
302 } else {
303 // Request is to dump statsd report data.
304 if (asProto) {
305 dumpIncidentSection(fd);
306 } else {
307 dprintf(fd, "Non-proto format of stats data dump not available; see proto version.\n");
308 }
Tej Singh41b3f9a2018-04-03 17:06:35 -0700309 }
Yao Chen884c8c12018-01-26 10:36:25 -0800310
Joe Onorato5dcbc6c2017-08-29 15:13:58 -0700311 return NO_ERROR;
312}
313
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700314/**
Tej Singh41b3f9a2018-04-03 17:06:35 -0700315 * Write debugging data about statsd in text or proto format.
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700316 */
Bookatzff71cad2018-09-20 17:17:49 -0700317void StatsService::dumpStatsdStats(int out, bool verbose, bool proto) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700318 if (proto) {
319 vector<uint8_t> data;
320 StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
321 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700322 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700323 }
324 } else {
325 StatsdStats::getInstance().dumpStats(out);
326 mProcessor->dumpStates(out, verbose);
327 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700328}
329
330/**
Bookatzff71cad2018-09-20 17:17:49 -0700331 * Write stats report data in StatsDataDumpProto incident section format.
332 */
333void StatsService::dumpIncidentSection(int out) {
334 ProtoOutputStream proto;
335 for (const ConfigKey& configKey : mConfigManager->GetAllConfigKeys()) {
336 uint64_t reportsListToken =
337 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS_LIST);
338 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(),
339 true /* includeCurrentBucket */, false /* erase_data */,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000340 ADB_DUMP,
341 FAST,
342 &proto);
Bookatzff71cad2018-09-20 17:17:49 -0700343 proto.end(reportsListToken);
344 proto.flush(out);
Bookatzc71d9012018-12-19 12:28:38 -0800345 proto.clear();
Bookatzff71cad2018-09-20 17:17:49 -0700346 }
347}
348
349/**
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700350 * Implementation of the adb shell cmd stats command.
351 */
Yao Chena80e5c02018-09-04 13:55:29 -0700352status_t StatsService::command(int in, int out, int err, Vector<String8>& args,
353 sp<IResultReceiver> resultReceiver) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600354 uid_t uid = IPCThreadState::self()->getCallingUid();
355 if (uid != AID_ROOT && uid != AID_SHELL) {
356 return PERMISSION_DENIED;
357 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700358
359 const int argCount = args.size();
360 if (argCount >= 1) {
361 // adb shell cmd stats config ...
David Chen0656b7a2017-09-13 15:53:39 -0700362 if (!args[0].compare(String8("config"))) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700363 return cmd_config(in, out, err, args);
David Chen0656b7a2017-09-13 15:53:39 -0700364 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700365
David Chende701692017-10-05 13:16:02 -0700366 if (!args[0].compare(String8("print-uid-map"))) {
Yao Chend10f7b12017-12-18 12:53:50 -0800367 return cmd_print_uid_map(out, args);
David Chende701692017-10-05 13:16:02 -0700368 }
Yao Chen729093d2017-10-16 10:33:26 -0700369
370 if (!args[0].compare(String8("dump-report"))) {
Bookatzff71cad2018-09-20 17:17:49 -0700371 return cmd_dump_report(out, args);
Yao Chen729093d2017-10-16 10:33:26 -0700372 }
David Chen1481fe12017-10-16 13:16:34 -0700373
374 if (!args[0].compare(String8("pull-source")) && args.size() > 1) {
375 return cmd_print_pulled_metrics(out, args);
376 }
David Chenadaf8b32017-11-03 15:42:08 -0700377
378 if (!args[0].compare(String8("send-broadcast"))) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800379 return cmd_trigger_broadcast(out, args);
380 }
381
382 if (!args[0].compare(String8("print-stats"))) {
Yao Chenb3561512017-11-21 18:07:17 -0800383 return cmd_print_stats(out, args);
David Chenadaf8b32017-11-03 15:42:08 -0700384 }
yro87d983c2017-11-14 21:31:43 -0800385
Yao Chen8d9989b2017-11-18 18:54:50 -0800386 if (!args[0].compare(String8("meminfo"))) {
387 return cmd_dump_memory_info(out);
388 }
yro947fbce2017-11-15 22:50:23 -0800389
390 if (!args[0].compare(String8("write-to-disk"))) {
391 return cmd_write_data_to_disk(out);
392 }
Bookatzb223c4e2018-02-01 15:35:04 -0800393
David Chen0b5c90c2018-01-25 16:51:49 -0800394 if (!args[0].compare(String8("log-app-breadcrumb"))) {
395 return cmd_log_app_breadcrumb(out, args);
Bookatzb223c4e2018-02-01 15:35:04 -0800396 }
Chenjie Yufa22d652018-02-05 14:37:48 -0800397
Tej Singh53f9dee2019-04-30 17:45:54 -0700398 if (!args[0].compare(String8("log-binary-push"))) {
399 return cmd_log_binary_push(out, args);
400 }
401
Chenjie Yufa22d652018-02-05 14:37:48 -0800402 if (!args[0].compare(String8("clear-puller-cache"))) {
403 return cmd_clear_puller_cache(out);
404 }
Yao Chen876889c2018-05-02 11:16:16 -0700405
406 if (!args[0].compare(String8("print-logs"))) {
407 return cmd_print_logs(out, args);
408 }
Tej Singh6ede28b2019-01-29 17:06:54 -0800409 if (!args[0].compare(String8("send-active-configs"))) {
410 return cmd_trigger_active_config_broadcast(out, args);
411 }
Yao Chena80e5c02018-09-04 13:55:29 -0700412 if (!args[0].compare(String8("data-subscribe"))) {
413 if (mShellSubscriber == nullptr) {
Yao Chen41e606c2018-10-05 15:54:11 -0700414 mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
Yao Chena80e5c02018-09-04 13:55:29 -0700415 }
Yao Chen35cb8d62019-01-03 16:49:14 -0800416 int timeoutSec = -1;
417 if (argCount >= 2) {
418 timeoutSec = atoi(args[1].c_str());
419 }
420 mShellSubscriber->startNewSubscription(in, out, resultReceiver, timeoutSec);
Yao Chena80e5c02018-09-04 13:55:29 -0700421 return NO_ERROR;
422 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700423 }
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700424
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700425 print_cmd_help(out);
Joe Onorato2cbc2cc2017-08-30 17:03:23 -0700426 return NO_ERROR;
427}
428
Yao Chena80e5c02018-09-04 13:55:29 -0700429void StatsService::print_cmd_help(int out) {
430 dprintf(out,
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700431 "usage: adb shell cmd stats print-stats-log [tag_required] "
432 "[timestamp_nsec_optional]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700433 dprintf(out, "\n");
434 dprintf(out, "\n");
435 dprintf(out, "usage: adb shell cmd stats meminfo\n");
436 dprintf(out, "\n");
437 dprintf(out, " Prints the malloc debug information. You need to run the following first: \n");
438 dprintf(out, " # adb shell stop\n");
439 dprintf(out, " # adb shell setprop libc.debug.malloc.program statsd \n");
440 dprintf(out, " # adb shell setprop libc.debug.malloc.options backtrace \n");
441 dprintf(out, " # adb shell start\n");
442 dprintf(out, "\n");
443 dprintf(out, "\n");
444 dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
445 dprintf(out, "\n");
446 dprintf(out, " Prints the UID, app name, version mapping.\n");
447 dprintf(out, " PKG Optional package name to print the uids of the package\n");
448 dprintf(out, "\n");
449 dprintf(out, "\n");
450 dprintf(out, "usage: adb shell cmd stats pull-source [int] \n");
451 dprintf(out, "\n");
452 dprintf(out, " Prints the output of a pulled metrics source (int indicates source)\n");
453 dprintf(out, "\n");
454 dprintf(out, "\n");
455 dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
456 dprintf(out, "\n");
457 dprintf(out, " Flushes all data on memory to disk.\n");
458 dprintf(out, "\n");
459 dprintf(out, "\n");
460 dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
461 dprintf(out, " Writes an AppBreadcrumbReported event to the statslog buffer.\n");
462 dprintf(out, " UID The uid to use. It is only possible to pass a UID\n");
463 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
464 dprintf(out, " uid is used.\n");
465 dprintf(out, " LABEL Integer in [0, 15], as per atoms.proto.\n");
466 dprintf(out, " STATE Integer in [0, 3], as per atoms.proto.\n");
467 dprintf(out, "\n");
468 dprintf(out, "\n");
Tej Singh53f9dee2019-04-30 17:45:54 -0700469 dprintf(out,
470 "usage: adb shell cmd stats log-binary-push NAME VERSION STAGING ROLLBACK_ENABLED "
471 "LOW_LATENCY STATE EXPERIMENT_IDS\n");
472 dprintf(out, " Log a binary push state changed event.\n");
473 dprintf(out, " NAME The train name.\n");
474 dprintf(out, " VERSION The train version code.\n");
475 dprintf(out, " STAGING If this train requires a restart.\n");
476 dprintf(out, " ROLLBACK_ENABLED If rollback should be enabled for this install.\n");
477 dprintf(out, " LOW_LATENCY If the train requires low latency monitoring.\n");
478 dprintf(out, " STATE The status of the train push.\n");
479 dprintf(out, " Integer value of the enum in atoms.proto.\n");
480 dprintf(out, " EXPERIMENT_IDS Comma separated list of experiment ids.\n");
481 dprintf(out, " Leave blank for none.\n");
482 dprintf(out, "\n");
483 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700484 dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
485 dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
486 dprintf(out, "\n");
487 dprintf(out, " Adds, updates or removes a configuration. The proto should be in\n");
488 dprintf(out, " wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
489 dprintf(out, " provided, then all configs will be removed from memory and disk.\n");
490 dprintf(out, "\n");
491 dprintf(out, " UID The uid to use. It is only possible to pass the UID\n");
492 dprintf(out, " parameter on eng builds. If UID is omitted the calling\n");
493 dprintf(out, " uid is used.\n");
494 dprintf(out, " NAME The per-uid name to use\n");
495 dprintf(out, "\n");
496 dprintf(out, "\n *Note: If both UID and NAME are omitted then all configs will\n");
497 dprintf(out, "\n be removed from memory and disk!\n");
498 dprintf(out, "\n");
499 dprintf(out,
Bookatz3e906582018-12-10 17:26:58 -0800500 "usage: adb shell cmd stats dump-report [UID] NAME [--keep_data] "
501 "[--include_current_bucket] [--proto]\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700502 dprintf(out, " Dump all metric data for a configuration.\n");
503 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
504 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
505 dprintf(out, " calling uid is used.\n");
506 dprintf(out, " NAME The name of the configuration\n");
Bookatz3e906582018-12-10 17:26:58 -0800507 dprintf(out, " --keep_data Do NOT erase the data upon dumping it.\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700508 dprintf(out, " --proto Print proto binary.\n");
509 dprintf(out, "\n");
510 dprintf(out, "\n");
511 dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
512 dprintf(out, " Send a broadcast that triggers the subscriber to fetch metrics.\n");
513 dprintf(out, " UID The uid of the configuration. It is only possible to pass\n");
514 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
515 dprintf(out, " calling uid is used.\n");
516 dprintf(out, " NAME The name of the configuration\n");
517 dprintf(out, "\n");
518 dprintf(out, "\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800519 dprintf(out,
520 "usage: adb shell cmd stats send-active-configs [--uid=UID] [--configs] "
521 "[NAME1] [NAME2] [NAME3..]\n");
522 dprintf(out, " Send a broadcast that informs the subscriber of the current active configs.\n");
523 dprintf(out, " --uid=UID The uid of the configurations. It is only possible to pass\n");
524 dprintf(out, " the UID parameter on eng builds. If UID is omitted the\n");
525 dprintf(out, " calling uid is used.\n");
526 dprintf(out, " --configs Send the list of configs in the name list instead of\n");
527 dprintf(out, " the currently active configs\n");
528 dprintf(out, " NAME LIST List of configuration names to be included in the broadcast.\n");
Tej Singh6ede28b2019-01-29 17:06:54 -0800529 dprintf(out, "\n");
530 dprintf(out, "\n");
Yao Chena80e5c02018-09-04 13:55:29 -0700531 dprintf(out, "usage: adb shell cmd stats print-stats\n");
532 dprintf(out, " Prints some basic stats.\n");
533 dprintf(out, " --proto Print proto binary instead of string format.\n");
534 dprintf(out, "\n");
535 dprintf(out, "\n");
536 dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
537 dprintf(out, " Clear cached puller data.\n");
538 dprintf(out, "\n");
539 dprintf(out, "usage: adb shell cmd stats print-logs\n");
540 dprintf(out, " Only works on eng build\n");
David Chenadaf8b32017-11-03 15:42:08 -0700541}
542
Yao Chena80e5c02018-09-04 13:55:29 -0700543status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800544 string name;
545 bool good = false;
546 int uid;
547 const int argCount = args.size();
548 if (argCount == 2) {
549 // Automatically pick the UID
550 uid = IPCThreadState::self()->getCallingUid();
David Chen1d7b0cd2017-11-15 14:20:04 -0800551 name.assign(args[1].c_str(), args[1].size());
552 good = true;
553 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800554 good = getUidFromArgs(args, 1, uid);
555 if (!good) {
556 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
557 "other UIDs on eng or userdebug builds.\n");
David Chen1d7b0cd2017-11-15 14:20:04 -0800558 }
Bookatzd2386572018-12-14 15:53:14 -0800559 name.assign(args[2].c_str(), args[2].size());
David Chen1d7b0cd2017-11-15 14:20:04 -0800560 }
561 if (!good) {
562 print_cmd_help(out);
563 return UNKNOWN_ERROR;
564 }
David Chend37bc232018-04-12 18:05:11 -0700565 ConfigKey key(uid, StrToInt64(name));
566 auto receiver = mConfigManager->GetConfigReceiver(key);
yro4d889e62017-11-17 15:44:48 -0800567 sp<IStatsCompanionService> sc = getStatsCompanionService();
David Chen661f7912018-01-22 17:46:24 -0800568 if (sc == nullptr) {
569 VLOG("Could not access statsCompanion");
570 } else if (receiver == nullptr) {
571 VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str())
572 } else {
David Chend37bc232018-04-12 18:05:11 -0700573 sc->sendDataBroadcast(receiver, mProcessor->getLastReportTimeNs(key));
yro74fed972017-11-27 14:42:42 -0800574 VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
575 args[2].c_str());
yro4d889e62017-11-17 15:44:48 -0800576 }
577
David Chenadaf8b32017-11-03 15:42:08 -0700578 return NO_ERROR;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700579}
580
Tej Singh6ede28b2019-01-29 17:06:54 -0800581status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
582 const int argCount = args.size();
583 int uid;
584 vector<int64_t> configIds;
585 if (argCount == 1) {
586 // Automatically pick the uid and send a broadcast that has no active configs.
587 uid = IPCThreadState::self()->getCallingUid();
588 mProcessor->GetActiveConfigs(uid, configIds);
589 } else {
590 int curArg = 1;
591 if(args[curArg].find("--uid=") == 0) {
592 string uidArgStr(args[curArg].c_str());
593 string uidStr = uidArgStr.substr(6);
594 if (!getUidFromString(uidStr.c_str(), uid)) {
595 dprintf(out, "Invalid UID. Note that the config can only be set for "
596 "other UIDs on eng or userdebug builds.\n");
597 return UNKNOWN_ERROR;
598 }
599 curArg++;
600 } else {
601 uid = IPCThreadState::self()->getCallingUid();
602 }
603 if (curArg == argCount || args[curArg] != "--configs") {
604 VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
605 mProcessor->GetActiveConfigs(uid, configIds);
606 } else {
607 // Flag specified, use the given list of configs.
608 curArg++;
609 for (int i = curArg; i < argCount; i++) {
610 char* endp;
611 int64_t configID = strtoll(args[i].c_str(), &endp, 10);
612 if (endp == args[i].c_str() || *endp != '\0') {
613 dprintf(out, "Error parsing config ID.\n");
614 return UNKNOWN_ERROR;
615 }
616 VLOG("Adding config id %ld", static_cast<long>(configID));
617 configIds.push_back(configID);
618 }
619 }
620 }
621 auto receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
622 sp<IStatsCompanionService> sc = getStatsCompanionService();
623 if (sc == nullptr) {
624 VLOG("Could not access statsCompanion");
625 } else if (receiver == nullptr) {
626 VLOG("Could not find receiver for uid %d", uid);
627 } else {
628 sc->sendActiveConfigsChangedBroadcast(receiver, configIds);
629 VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
630 }
631 return NO_ERROR;
632}
633
Yao Chena80e5c02018-09-04 13:55:29 -0700634status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700635 const int argCount = args.size();
636 if (argCount >= 2) {
637 if (args[1] == "update" || args[1] == "remove") {
638 bool good = false;
639 int uid = -1;
640 string name;
641
642 if (argCount == 3) {
643 // Automatically pick the UID
644 uid = IPCThreadState::self()->getCallingUid();
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700645 name.assign(args[2].c_str(), args[2].size());
646 good = true;
647 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800648 good = getUidFromArgs(args, 2, uid);
649 if (!good) {
650 dprintf(err, "Invalid UID. Note that the config can only be set for "
651 "other UIDs on eng or userdebug builds.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700652 }
Bookatzd2386572018-12-14 15:53:14 -0800653 name.assign(args[3].c_str(), args[3].size());
yroe5f82922018-01-22 18:37:27 -0800654 } else if (argCount == 2 && args[1] == "remove") {
655 good = true;
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700656 }
657
658 if (!good) {
659 // If arg parsing failed, print the help text and return an error.
660 print_cmd_help(out);
661 return UNKNOWN_ERROR;
662 }
663
664 if (args[1] == "update") {
yro255f72e2018-02-26 15:15:17 -0800665 char* endp;
666 int64_t configID = strtoll(name.c_str(), &endp, 10);
667 if (endp == name.c_str() || *endp != '\0') {
Yao Chena80e5c02018-09-04 13:55:29 -0700668 dprintf(err, "Error parsing config ID.\n");
yro255f72e2018-02-26 15:15:17 -0800669 return UNKNOWN_ERROR;
670 }
671
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700672 // Read stream into buffer.
673 string buffer;
Yao Chena80e5c02018-09-04 13:55:29 -0700674 if (!android::base::ReadFdToString(in, &buffer)) {
675 dprintf(err, "Error reading stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700676 return UNKNOWN_ERROR;
677 }
678
679 // Parse buffer.
680 StatsdConfig config;
681 if (!config.ParseFromString(buffer)) {
Yao Chena80e5c02018-09-04 13:55:29 -0700682 dprintf(err, "Error parsing proto stream for StatsConfig.\n");
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700683 return UNKNOWN_ERROR;
684 }
685
686 // Add / update the config.
yro255f72e2018-02-26 15:15:17 -0800687 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700688 } else {
yro74fed972017-11-27 14:42:42 -0800689 if (argCount == 2) {
690 cmd_remove_all_configs(out);
691 } else {
692 // Remove the config.
Yangster-mac94e197c2018-01-02 16:03:03 -0800693 mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
yro74fed972017-11-27 14:42:42 -0800694 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700695 }
696
697 return NO_ERROR;
698 }
David Chen0656b7a2017-09-13 15:53:39 -0700699 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700700 print_cmd_help(out);
701 return UNKNOWN_ERROR;
702}
703
Bookatzff71cad2018-09-20 17:17:49 -0700704status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
Yao Chen729093d2017-10-16 10:33:26 -0700705 if (mProcessor != nullptr) {
Chenjie Yub236c862017-11-28 22:20:44 -0800706 int argCount = args.size();
Yao Chen729093d2017-10-16 10:33:26 -0700707 bool good = false;
Chenjie Yub236c862017-11-28 22:20:44 -0800708 bool proto = false;
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700709 bool includeCurrentBucket = false;
Bookatz3e906582018-12-10 17:26:58 -0800710 bool eraseData = true;
Yao Chen729093d2017-10-16 10:33:26 -0700711 int uid;
712 string name;
Chenjie Yub236c862017-11-28 22:20:44 -0800713 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
714 proto = true;
715 argCount -= 1;
716 }
Chenjie Yubd1a28f2018-07-17 14:55:19 -0700717 if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
718 includeCurrentBucket = true;
719 argCount -= 1;
720 }
Bookatz3e906582018-12-10 17:26:58 -0800721 if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
722 eraseData = false;
723 argCount -= 1;
724 }
Yao Chen729093d2017-10-16 10:33:26 -0700725 if (argCount == 2) {
726 // Automatically pick the UID
727 uid = IPCThreadState::self()->getCallingUid();
Yao Chen5154a3792017-10-30 22:57:06 -0700728 name.assign(args[1].c_str(), args[1].size());
Yao Chen729093d2017-10-16 10:33:26 -0700729 good = true;
730 } else if (argCount == 3) {
Bookatzd2386572018-12-14 15:53:14 -0800731 good = getUidFromArgs(args, 1, uid);
732 if (!good) {
733 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
734 "other UIDs on eng or userdebug builds.\n");
Yao Chen729093d2017-10-16 10:33:26 -0700735 }
Bookatzd2386572018-12-14 15:53:14 -0800736 name.assign(args[2].c_str(), args[2].size());
Yao Chen729093d2017-10-16 10:33:26 -0700737 }
738 if (good) {
David Chen1d7b0cd2017-11-15 14:20:04 -0800739 vector<uint8_t> data;
David Chen926fc752018-02-23 13:31:43 -0800740 mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000741 includeCurrentBucket, eraseData, ADB_DUMP,
742 NO_TIME_CONSTRAINTS,
743 &data);
Chenjie Yub236c862017-11-28 22:20:44 -0800744 if (proto) {
745 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700746 dprintf(out, "%c", data[i]);
Chenjie Yub236c862017-11-28 22:20:44 -0800747 }
748 } else {
Bookatzff71cad2018-09-20 17:17:49 -0700749 dprintf(out, "Non-proto stats data dump not currently supported.\n");
Chenjie Yub236c862017-11-28 22:20:44 -0800750 }
Yao Chen729093d2017-10-16 10:33:26 -0700751 return android::OK;
752 } else {
753 // If arg parsing failed, print the help text and return an error.
754 print_cmd_help(out);
755 return UNKNOWN_ERROR;
756 }
757 } else {
Yao Chena80e5c02018-09-04 13:55:29 -0700758 dprintf(out, "Log processor does not exist...\n");
Yao Chen729093d2017-10-16 10:33:26 -0700759 return UNKNOWN_ERROR;
760 }
761}
762
Yao Chena80e5c02018-09-04 13:55:29 -0700763status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
Tej Singh41b3f9a2018-04-03 17:06:35 -0700764 int argCount = args.size();
765 bool proto = false;
766 if (!std::strcmp("--proto", args[argCount-1].c_str())) {
767 proto = true;
768 argCount -= 1;
David Chen1d7b0cd2017-11-15 14:20:04 -0800769 }
Yao Chenb3561512017-11-21 18:07:17 -0800770 StatsdStats& statsdStats = StatsdStats::getInstance();
Tej Singh41b3f9a2018-04-03 17:06:35 -0700771 if (proto) {
772 vector<uint8_t> data;
773 statsdStats.dumpStats(&data, false); // does not reset statsdStats.
774 for (size_t i = 0; i < data.size(); i ++) {
Yao Chena80e5c02018-09-04 13:55:29 -0700775 dprintf(out, "%c", data[i]);
Tej Singh41b3f9a2018-04-03 17:06:35 -0700776 }
777
778 } else {
779 vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
780 for (const ConfigKey& key : configs) {
Yao Chena80e5c02018-09-04 13:55:29 -0700781 dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
Tej Singh41b3f9a2018-04-03 17:06:35 -0700782 mProcessor->GetMetricsSize(key));
783 }
784 statsdStats.dumpStats(out);
785 }
David Chen1d7b0cd2017-11-15 14:20:04 -0800786 return NO_ERROR;
787}
788
Yao Chena80e5c02018-09-04 13:55:29 -0700789status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
Yao Chend10f7b12017-12-18 12:53:50 -0800790 if (args.size() > 1) {
791 string pkg;
792 pkg.assign(args[1].c_str(), args[1].size());
793 auto uids = mUidMap->getAppUid(pkg);
Yao Chena80e5c02018-09-04 13:55:29 -0700794 dprintf(out, "%s -> [ ", pkg.c_str());
Yao Chend10f7b12017-12-18 12:53:50 -0800795 for (const auto& uid : uids) {
Yao Chena80e5c02018-09-04 13:55:29 -0700796 dprintf(out, "%d ", uid);
Yao Chend10f7b12017-12-18 12:53:50 -0800797 }
Yao Chena80e5c02018-09-04 13:55:29 -0700798 dprintf(out, "]\n");
Yao Chend10f7b12017-12-18 12:53:50 -0800799 } else {
800 mUidMap->printUidMap(out);
801 }
Joe Onorato9fc9edf2017-10-15 20:08:52 -0700802 return NO_ERROR;
David Chen0656b7a2017-09-13 15:53:39 -0700803}
804
Yao Chena80e5c02018-09-04 13:55:29 -0700805status_t StatsService::cmd_write_data_to_disk(int out) {
806 dprintf(out, "Writing data to disk\n");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +0000807 mProcessor->WriteDataToDisk(ADB_DUMP, NO_TIME_CONSTRAINTS);
yro947fbce2017-11-15 22:50:23 -0800808 return NO_ERROR;
809}
810
Yao Chena80e5c02018-09-04 13:55:29 -0700811status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
Bookatzb223c4e2018-02-01 15:35:04 -0800812 bool good = false;
813 int32_t uid;
814 int32_t label;
815 int32_t state;
816 const int argCount = args.size();
817 if (argCount == 3) {
818 // Automatically pick the UID
819 uid = IPCThreadState::self()->getCallingUid();
820 label = atoi(args[1].c_str());
821 state = atoi(args[2].c_str());
822 good = true;
823 } else if (argCount == 4) {
Bookatzd2386572018-12-14 15:53:14 -0800824 good = getUidFromArgs(args, 1, uid);
825 if (!good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700826 dprintf(out,
Bookatzd2386572018-12-14 15:53:14 -0800827 "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
828 "done for other UIDs on eng or userdebug builds.\n");
Bookatzb223c4e2018-02-01 15:35:04 -0800829 }
Bookatzd2386572018-12-14 15:53:14 -0800830 label = atoi(args[2].c_str());
831 state = atoi(args[3].c_str());
Bookatzb223c4e2018-02-01 15:35:04 -0800832 }
833 if (good) {
Yao Chena80e5c02018-09-04 13:55:29 -0700834 dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
David Chen0b5c90c2018-01-25 16:51:49 -0800835 android::util::stats_write(android::util::APP_BREADCRUMB_REPORTED, uid, label, state);
Bookatzb223c4e2018-02-01 15:35:04 -0800836 } else {
837 print_cmd_help(out);
838 return UNKNOWN_ERROR;
839 }
840 return NO_ERROR;
841}
842
Tej Singh53f9dee2019-04-30 17:45:54 -0700843status_t StatsService::cmd_log_binary_push(int out, const Vector<String8>& args) {
844 // Security checks are done in the sendBinaryPushStateChanged atom.
845 const int argCount = args.size();
846 if (argCount != 7 && argCount != 8) {
847 dprintf(out, "Incorrect number of argument supplied\n");
848 return UNKNOWN_ERROR;
849 }
850 android::String16 trainName = android::String16(args[1].c_str());
851 int64_t trainVersion = strtoll(args[2].c_str(), nullptr, 10);
852 int options = 0;
853 if (args[3] == "1") {
854 options = options | IStatsManager::FLAG_REQUIRE_STAGING;
855 }
856 if (args[4] == "1") {
857 options = options | IStatsManager::FLAG_ROLLBACK_ENABLED;
858 }
859 if (args[5] == "1") {
860 options = options | IStatsManager::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
861 }
862 int32_t state = atoi(args[6].c_str());
863 vector<int64_t> experimentIds;
864 if (argCount == 8) {
865 vector<string> experimentIdsString = android::base::Split(string(args[7].c_str()), ",");
866 for (string experimentIdString : experimentIdsString) {
867 int64_t experimentId = strtoll(experimentIdString.c_str(), nullptr, 10);
868 experimentIds.push_back(experimentId);
869 }
870 }
871 dprintf(out, "Logging BinaryPushStateChanged\n");
872 sendBinaryPushStateChangedAtom(trainName, trainVersion, options, state, experimentIds);
873 return NO_ERROR;
874}
875
Yao Chena80e5c02018-09-04 13:55:29 -0700876status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
David Chen1481fe12017-10-16 13:16:34 -0700877 int s = atoi(args[1].c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700878 vector<shared_ptr<LogEvent> > stats;
Chenjie Yu0bd73db2018-12-16 07:37:04 -0800879 if (mPullerManager->Pull(s, &stats)) {
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700880 for (const auto& it : stats) {
Yao Chena80e5c02018-09-04 13:55:29 -0700881 dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700882 }
Yao Chena80e5c02018-09-04 13:55:29 -0700883 dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700884 return NO_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700885 }
Chenjie Yu5305e1d2017-10-31 13:49:36 -0700886 return UNKNOWN_ERROR;
David Chen1481fe12017-10-16 13:16:34 -0700887}
888
Yao Chena80e5c02018-09-04 13:55:29 -0700889status_t StatsService::cmd_remove_all_configs(int out) {
890 dprintf(out, "Removing all configs...\n");
yro74fed972017-11-27 14:42:42 -0800891 VLOG("StatsService::cmd_remove_all_configs was called");
892 mConfigManager->RemoveAllConfigs();
yro947fbce2017-11-15 22:50:23 -0800893 StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
yro87d983c2017-11-14 21:31:43 -0800894 return NO_ERROR;
895}
896
Yao Chena80e5c02018-09-04 13:55:29 -0700897status_t StatsService::cmd_dump_memory_info(int out) {
898 dprintf(out, "meminfo not available.\n");
Yao Chen8d9989b2017-11-18 18:54:50 -0800899 return NO_ERROR;
900}
901
Yao Chena80e5c02018-09-04 13:55:29 -0700902status_t StatsService::cmd_clear_puller_cache(int out) {
Chenjie Yufa22d652018-02-05 14:37:48 -0800903 IPCThreadState* ipc = IPCThreadState::self();
Yangster-mac932ecec2018-02-01 10:23:52 -0800904 VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
905 ipc->getCallingPid(), ipc->getCallingUid());
Chenjie Yufa22d652018-02-05 14:37:48 -0800906 if (checkCallingPermission(String16(kPermissionDump))) {
Chenjie Yue2219202018-06-08 10:07:51 -0700907 int cleared = mPullerManager->ForceClearPullerCache();
Yao Chena80e5c02018-09-04 13:55:29 -0700908 dprintf(out, "Puller removed %d cached data!\n", cleared);
Chenjie Yufa22d652018-02-05 14:37:48 -0800909 return NO_ERROR;
910 } else {
911 return PERMISSION_DENIED;
912 }
Chenjie Yue72252b2018-02-01 13:19:35 -0800913}
914
Yao Chena80e5c02018-09-04 13:55:29 -0700915status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
Yao Chen876889c2018-05-02 11:16:16 -0700916 IPCThreadState* ipc = IPCThreadState::self();
917 VLOG("StatsService::cmd_print_logs with Pid %i, Uid %i", ipc->getCallingPid(),
918 ipc->getCallingUid());
919 if (checkCallingPermission(String16(kPermissionDump))) {
920 bool enabled = true;
921 if (args.size() >= 2) {
922 enabled = atoi(args[1].c_str()) != 0;
923 }
924 mProcessor->setPrintLogs(enabled);
925 return NO_ERROR;
926 } else {
927 return PERMISSION_DENIED;
928 }
929}
930
Bookatzd2386572018-12-14 15:53:14 -0800931bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
Tej Singh6ede28b2019-01-29 17:06:54 -0800932 return getUidFromString(args[uidArgIndex].c_str(), uid);
933}
934
935bool StatsService::getUidFromString(const char* s, int32_t& uid) {
Bookatzd2386572018-12-14 15:53:14 -0800936 if (*s == '\0') {
937 return false;
938 }
939 char* endc = NULL;
940 int64_t longUid = strtol(s, &endc, 0);
941 if (*endc != '\0') {
942 return false;
943 }
944 int32_t goodUid = static_cast<int32_t>(longUid);
945 if (longUid < 0 || static_cast<uint64_t>(longUid) != static_cast<uid_t>(goodUid)) {
946 return false; // It was not of uid_t type.
947 }
948 uid = goodUid;
949
950 int32_t callingUid = IPCThreadState::self()->getCallingUid();
951 return mEngBuild // UserDebug/EngBuild are allowed to impersonate uids.
952 || (callingUid == goodUid) // Anyone can 'impersonate' themselves.
953 || (callingUid == AID_ROOT && goodUid == AID_SHELL); // ROOT can impersonate SHELL.
954}
955
Dianne Hackborn3accca02013-09-20 09:32:11 -0700956Status StatsService::informAllUidData(const vector<int32_t>& uid, const vector<int64_t>& version,
dwchen730403e2018-10-29 11:41:56 -0700957 const vector<String16>& version_string,
958 const vector<String16>& app,
959 const vector<String16>& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600960 ENFORCE_UID(AID_SYSTEM);
961
yro74fed972017-11-27 14:42:42 -0800962 VLOG("StatsService::informAllUidData was called");
dwchen730403e2018-10-29 11:41:56 -0700963 mUidMap->updateMap(getElapsedRealtimeNs(), uid, version, version_string, app, installer);
yro74fed972017-11-27 14:42:42 -0800964 VLOG("StatsService::informAllUidData succeeded");
David Chende701692017-10-05 13:16:02 -0700965
966 return Status::ok();
967}
968
dwchen730403e2018-10-29 11:41:56 -0700969Status StatsService::informOnePackage(const String16& app, int32_t uid, int64_t version,
970 const String16& version_string, const String16& installer) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600971 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700972
Jeff Sharkey6b649252018-04-16 09:50:22 -0600973 VLOG("StatsService::informOnePackage was called");
dwchen730403e2018-10-29 11:41:56 -0700974 mUidMap->updateApp(getElapsedRealtimeNs(), app, uid, version, version_string, installer);
David Chende701692017-10-05 13:16:02 -0700975 return Status::ok();
976}
977
978Status StatsService::informOnePackageRemoved(const String16& app, int32_t uid) {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600979 ENFORCE_UID(AID_SYSTEM);
David Chende701692017-10-05 13:16:02 -0700980
Jeff Sharkey6b649252018-04-16 09:50:22 -0600981 VLOG("StatsService::informOnePackageRemoved was called");
David Chenbd125272018-04-04 19:02:50 -0700982 mUidMap->removeApp(getElapsedRealtimeNs(), app, uid);
yro01924022018-02-20 18:20:49 -0800983 mConfigManager->RemoveConfigs(uid);
David Chende701692017-10-05 13:16:02 -0700984 return Status::ok();
985}
986
Yao Chenef99c4f2017-09-22 16:26:54 -0700987Status StatsService::informAnomalyAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -0600988 ENFORCE_UID(AID_SYSTEM);
989
yro74fed972017-11-27 14:42:42 -0800990 VLOG("StatsService::informAnomalyAlarmFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -0700991 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -0800992 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
993 mAnomalyAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
994 if (alarmSet.size() > 0) {
Bookatz66fe0612018-02-07 18:51:48 -0800995 VLOG("Found an anomaly alarm that fired.");
Yangster-mac932ecec2018-02-01 10:23:52 -0800996 mProcessor->onAnomalyAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
Bookatz66fe0612018-02-07 18:51:48 -0800997 } else {
998 VLOG("Cannot find an anomaly alarm that fired. Perhaps it was recently cancelled.");
999 }
Bookatz1b0b1142017-09-08 11:58:42 -07001000 return Status::ok();
1001}
1002
Yangster-mac932ecec2018-02-01 10:23:52 -08001003Status StatsService::informAlarmForSubscriberTriggeringFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001004 ENFORCE_UID(AID_SYSTEM);
1005
Yangster-mac932ecec2018-02-01 10:23:52 -08001006 VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
Yangster-macb142cc82018-03-30 15:22:08 -07001007 int64_t currentTimeSec = getElapsedRealtimeSec();
Yangster-mac932ecec2018-02-01 10:23:52 -08001008 std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
1009 mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
1010 if (alarmSet.size() > 0) {
1011 VLOG("Found periodic alarm fired.");
1012 mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
1013 } else {
1014 ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
1015 }
1016 return Status::ok();
1017}
1018
Yao Chenef99c4f2017-09-22 16:26:54 -07001019Status StatsService::informPollAlarmFired() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001020 ENFORCE_UID(AID_SYSTEM);
1021
yro74fed972017-11-27 14:42:42 -08001022 VLOG("StatsService::informPollAlarmFired was called");
Yangster-mac15f6bbc2018-04-08 11:52:26 -07001023 mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
yro74fed972017-11-27 14:42:42 -08001024 VLOG("StatsService::informPollAlarmFired succeeded");
Bookatz1b0b1142017-09-08 11:58:42 -07001025 return Status::ok();
1026}
1027
Yao Chenef99c4f2017-09-22 16:26:54 -07001028Status StatsService::systemRunning() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001029 ENFORCE_UID(AID_SYSTEM);
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001030
1031 // When system_server is up and running, schedule the dropbox task to run.
yro74fed972017-11-27 14:42:42 -08001032 VLOG("StatsService::systemRunning");
Bookatzb487b552017-09-18 11:26:01 -07001033 sayHiToStatsCompanion();
Joe Onorato5dcbc6c2017-08-29 15:13:58 -07001034 return Status::ok();
1035}
1036
Yangster-mac892f3d32018-05-02 14:16:48 -07001037Status StatsService::informDeviceShutdown() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001038 ENFORCE_UID(AID_SYSTEM);
Chenjie Yue36018b2018-04-16 15:18:30 -07001039 VLOG("StatsService::informDeviceShutdown");
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001040 mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001041 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
yro947fbce2017-11-15 22:50:23 -08001042 return Status::ok();
1043}
1044
Yao Chenef99c4f2017-09-22 16:26:54 -07001045void StatsService::sayHiToStatsCompanion() {
Bookatzb487b552017-09-18 11:26:01 -07001046 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1047 if (statsCompanion != nullptr) {
yro74fed972017-11-27 14:42:42 -08001048 VLOG("Telling statsCompanion that statsd is ready");
Bookatzb487b552017-09-18 11:26:01 -07001049 statsCompanion->statsdReady();
1050 } else {
yro74fed972017-11-27 14:42:42 -08001051 VLOG("Could not access statsCompanion");
Bookatzb487b552017-09-18 11:26:01 -07001052 }
1053}
1054
Yao Chenef99c4f2017-09-22 16:26:54 -07001055Status StatsService::statsCompanionReady() {
Jeff Sharkey6b649252018-04-16 09:50:22 -06001056 ENFORCE_UID(AID_SYSTEM);
1057
yro74fed972017-11-27 14:42:42 -08001058 VLOG("StatsService::statsCompanionReady was called");
Bookatzb487b552017-09-18 11:26:01 -07001059 sp<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1060 if (statsCompanion == nullptr) {
Yao Chenef99c4f2017-09-22 16:26:54 -07001061 return Status::fromExceptionCode(
1062 Status::EX_NULL_POINTER,
1063 "statscompanion unavailable despite it contacting statsd!");
Bookatzb487b552017-09-18 11:26:01 -07001064 }
yro74fed972017-11-27 14:42:42 -08001065 VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001066 IInterface::asBinder(statsCompanion)->linkToDeath(this);
Chenjie Yue2219202018-06-08 10:07:51 -07001067 mPullerManager->SetStatsCompanionService(statsCompanion);
Yangster-mac932ecec2018-02-01 10:23:52 -08001068 mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
1069 mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
Bookatzc6977972018-01-16 16:55:05 -08001070 SubscriberReporter::getInstance().setStatsCompanionService(statsCompanion);
Bookatzb487b552017-09-18 11:26:01 -07001071 return Status::ok();
1072}
1073
Joe Onorato9fc9edf2017-10-15 20:08:52 -07001074void StatsService::Startup() {
1075 mConfigManager->Startup();
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001076 mProcessor->LoadActiveConfigsFromDisk();
Bookatz906a35c2017-09-20 15:26:44 -07001077}
1078
Yangster-mac97e7d202018-10-09 11:05:39 -07001079void StatsService::Terminate() {
1080 ALOGI("StatsService::Terminating");
1081 if (mProcessor != nullptr) {
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001082 mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED, FAST);
Muhammad Qureshi844694b2019-04-05 10:10:40 -07001083 mProcessor->SaveActiveConfigsToDisk(getElapsedRealtimeNs());
Yangster-mac97e7d202018-10-09 11:05:39 -07001084 }
1085}
1086
Yao Chen0f861862019-03-27 11:51:15 -07001087// Test only interface!!!
Yao Chen3ff3a492018-08-06 16:17:37 -07001088void StatsService::OnLogEvent(LogEvent* event) {
1089 mProcessor->OnLogEvent(event);
Yao Chena80e5c02018-09-04 13:55:29 -07001090 if (mShellSubscriber != nullptr) {
1091 mShellSubscriber->onLogEvent(*event);
1092 }
Bookatz906a35c2017-09-20 15:26:44 -07001093}
1094
Jeff Sharkey6b649252018-04-16 09:50:22 -06001095Status StatsService::getData(int64_t key, const String16& packageName, vector<uint8_t>* output) {
1096 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1097
David Chenadaf8b32017-11-03 15:42:08 -07001098 IPCThreadState* ipc = IPCThreadState::self();
yro74fed972017-11-27 14:42:42 -08001099 VLOG("StatsService::getData with Pid %i, Uid %i", ipc->getCallingPid(), ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001100 ConfigKey configKey(ipc->getCallingUid(), key);
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001101 // The dump latency does not matter here since we do not include the current bucket, we do not
1102 // need to pull any new data anyhow.
David Chen56ae0d92018-05-11 16:00:22 -07001103 mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), false /* include_current_bucket*/,
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001104 true /* erase_data */, GET_DATA_CALLED, FAST, output);
Bookatz4f716292018-04-10 17:15:12 -07001105 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001106}
1107
Jeff Sharkey6b649252018-04-16 09:50:22 -06001108Status StatsService::getMetadata(const String16& packageName, vector<uint8_t>* output) {
1109 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1110
David Chen2e8f3802017-11-22 10:56:48 -08001111 IPCThreadState* ipc = IPCThreadState::self();
1112 VLOG("StatsService::getMetadata with Pid %i, Uid %i", ipc->getCallingPid(),
1113 ipc->getCallingUid());
Bookatz4f716292018-04-10 17:15:12 -07001114 StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
1115 return Status::ok();
David Chen2e8f3802017-11-22 10:56:48 -08001116}
1117
Jeff Sharkey6b649252018-04-16 09:50:22 -06001118Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
1119 const String16& packageName) {
1120 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1121
David Chenadaf8b32017-11-03 15:42:08 -07001122 IPCThreadState* ipc = IPCThreadState::self();
Bookatz4f716292018-04-10 17:15:12 -07001123 if (addConfigurationChecked(ipc->getCallingUid(), key, config)) {
David Chen661f7912018-01-22 17:46:24 -08001124 return Status::ok();
1125 } else {
Bookatz4f716292018-04-10 17:15:12 -07001126 ALOGE("Could not parse malformatted StatsdConfig");
1127 return Status::fromExceptionCode(binder::Status::EX_ILLEGAL_ARGUMENT,
1128 "config does not correspond to a StatsdConfig proto");
David Chen661f7912018-01-22 17:46:24 -08001129 }
1130}
1131
David Chen9fdd4032018-03-20 14:38:56 -07001132bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
1133 ConfigKey configKey(uid, key);
1134 StatsdConfig cfg;
1135 if (config.size() > 0) { // If the config is empty, skip parsing.
1136 if (!cfg.ParseFromArray(&config[0], config.size())) {
1137 return false;
1138 }
1139 }
1140 mConfigManager->UpdateConfig(configKey, cfg);
1141 return true;
1142}
1143
Jeff Sharkey6b649252018-04-16 09:50:22 -06001144Status StatsService::removeDataFetchOperation(int64_t key, const String16& packageName) {
1145 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1146
Bookatz4f716292018-04-10 17:15:12 -07001147 IPCThreadState* ipc = IPCThreadState::self();
1148 ConfigKey configKey(ipc->getCallingUid(), key);
1149 mConfigManager->RemoveConfigReceiver(configKey);
1150 return Status::ok();
David Chen661f7912018-01-22 17:46:24 -08001151}
1152
Jeff Sharkey6b649252018-04-16 09:50:22 -06001153Status StatsService::setDataFetchOperation(int64_t key,
1154 const sp<android::IBinder>& intentSender,
1155 const String16& packageName) {
1156 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1157
Bookatz4f716292018-04-10 17:15:12 -07001158 IPCThreadState* ipc = IPCThreadState::self();
1159 ConfigKey configKey(ipc->getCallingUid(), key);
1160 mConfigManager->SetConfigReceiver(configKey, intentSender);
David Chen48944902018-05-03 10:29:11 -07001161 if (StorageManager::hasConfigMetricsReport(configKey)) {
1162 VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
1163 configKey.ToString().c_str());
1164 mProcessor->noteOnDiskData(configKey);
1165 }
Bookatz4f716292018-04-10 17:15:12 -07001166 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001167}
1168
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001169Status StatsService::setActiveConfigsChangedOperation(const sp<android::IBinder>& intentSender,
1170 const String16& packageName,
1171 vector<int64_t>* output) {
1172 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1173
1174 IPCThreadState* ipc = IPCThreadState::self();
Tej Singh6ede28b2019-01-29 17:06:54 -08001175 int uid = ipc->getCallingUid();
1176 mConfigManager->SetActiveConfigsChangedReceiver(uid, intentSender);
1177 if (output != nullptr) {
1178 mProcessor->GetActiveConfigs(uid, *output);
1179 } else {
1180 ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
1181 }
Tej Singh2c9ef2a2019-01-22 11:33:51 -08001182 return Status::ok();
1183}
1184
1185Status StatsService::removeActiveConfigsChangedOperation(const String16& packageName) {
1186 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1187
1188 IPCThreadState* ipc = IPCThreadState::self();
1189 mConfigManager->RemoveActiveConfigsChangedReceiver(ipc->getCallingUid());
1190 return Status::ok();
1191}
1192
Jeff Sharkey6b649252018-04-16 09:50:22 -06001193Status StatsService::removeConfiguration(int64_t key, const String16& packageName) {
1194 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1195
Bookatz4f716292018-04-10 17:15:12 -07001196 IPCThreadState* ipc = IPCThreadState::self();
1197 ConfigKey configKey(ipc->getCallingUid(), key);
1198 mConfigManager->RemoveConfig(configKey);
1199 SubscriberReporter::getInstance().removeConfig(configKey);
1200 return Status::ok();
yro31eb67b2017-10-24 13:33:21 -07001201}
1202
Bookatzc6977972018-01-16 16:55:05 -08001203Status StatsService::setBroadcastSubscriber(int64_t configId,
1204 int64_t subscriberId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001205 const sp<android::IBinder>& intentSender,
1206 const String16& packageName) {
1207 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1208
Bookatzc6977972018-01-16 16:55:05 -08001209 VLOG("StatsService::setBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001210 IPCThreadState* ipc = IPCThreadState::self();
1211 ConfigKey configKey(ipc->getCallingUid(), configId);
1212 SubscriberReporter::getInstance()
1213 .setBroadcastSubscriber(configKey, subscriberId, intentSender);
1214 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001215}
1216
1217Status StatsService::unsetBroadcastSubscriber(int64_t configId,
Jeff Sharkey6b649252018-04-16 09:50:22 -06001218 int64_t subscriberId,
1219 const String16& packageName) {
1220 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1221
Bookatzc6977972018-01-16 16:55:05 -08001222 VLOG("StatsService::unsetBroadcastSubscriber called.");
Bookatz4f716292018-04-10 17:15:12 -07001223 IPCThreadState* ipc = IPCThreadState::self();
1224 ConfigKey configKey(ipc->getCallingUid(), configId);
1225 SubscriberReporter::getInstance()
1226 .unsetBroadcastSubscriber(configKey, subscriberId);
1227 return Status::ok();
Bookatzc6977972018-01-16 16:55:05 -08001228}
1229
yrobe6d7f92018-05-04 13:02:53 -07001230Status StatsService::sendAppBreadcrumbAtom(int32_t label, int32_t state) {
1231 // Permission check not necessary as it's meant for applications to write to
1232 // statsd.
1233 android::util::stats_write(util::APP_BREADCRUMB_REPORTED,
1234 IPCThreadState::self()->getCallingUid(), label,
1235 state);
1236 return Status::ok();
1237}
1238
Tej Singha0c89dd2019-01-25 16:39:18 -08001239Status StatsService::registerPullerCallback(int32_t atomTag,
1240 const sp<android::os::IStatsPullerCallback>& pullerCallback,
1241 const String16& packageName) {
1242 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1243
1244 VLOG("StatsService::registerPullerCallback called.");
1245 mPullerManager->RegisterPullerCallback(atomTag, pullerCallback);
1246 return Status::ok();
1247}
1248
1249Status StatsService::unregisterPullerCallback(int32_t atomTag, const String16& packageName) {
1250 ENFORCE_DUMP_AND_USAGE_STATS(packageName);
1251
1252 VLOG("StatsService::unregisterPullerCallback called.");
1253 mPullerManager->UnregisterPullerCallback(atomTag);
1254 return Status::ok();
1255}
1256
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001257Status StatsService::sendBinaryPushStateChangedAtom(const android::String16& trainNameIn,
1258 const int64_t trainVersionCodeIn,
1259 const int options,
1260 const int32_t state,
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001261 const std::vector<int64_t>& experimentIdsIn) {
Tej Singh53f9dee2019-04-30 17:45:54 -07001262 // Note: We skip the usage stats op check here since we do not have a package name.
1263 // This is ok since we are overloading the usage_stats permission.
1264 // This method only sends data, it does not receive it.
1265 pid_t pid = IPCThreadState::self()->getCallingPid();
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001266 uid_t uid = IPCThreadState::self()->getCallingUid();
Tej Singh53f9dee2019-04-30 17:45:54 -07001267 // Root, system, and shell always have access
1268 if (uid != AID_ROOT && uid != AID_SYSTEM && uid != AID_SHELL) {
1269 // Caller must be granted these permissions
1270 if (!checkCallingPermission(String16(kPermissionDump))) {
1271 return exception(binder::Status::EX_SECURITY,
1272 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1273 kPermissionDump));
1274 }
1275 if (!checkCallingPermission(String16(kPermissionUsage))) {
1276 return exception(binder::Status::EX_SECURITY,
1277 StringPrintf("UID %d / PID %d lacks permission %s", uid, pid,
1278 kPermissionUsage));
1279 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001280 }
1281
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001282 bool readTrainInfoSuccess = false;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001283 InstallTrainInfo trainInfoOnDisk;
1284 readTrainInfoSuccess = StorageManager::readTrainInfo(trainInfoOnDisk);
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001285
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001286 bool resetExperimentIds = false;
1287 int64_t trainVersionCode = trainVersionCodeIn;
1288 std::string trainNameUtf8 = std::string(String8(trainNameIn).string());
1289 if (readTrainInfoSuccess) {
1290 // Keep the old train version if we received an empty version.
1291 if (trainVersionCodeIn == -1) {
1292 trainVersionCode = trainInfoOnDisk.trainVersionCode;
1293 } else if (trainVersionCodeIn != trainInfoOnDisk.trainVersionCode) {
1294 // Reset experiment ids if we receive a new non-empty train version.
1295 resetExperimentIds = true;
1296 }
1297
1298 // Keep the old train name if we received an empty train name.
1299 if (trainNameUtf8.size() == 0) {
1300 trainNameUtf8 = trainInfoOnDisk.trainName;
1301 } else if (trainNameUtf8 != trainInfoOnDisk.trainName) {
1302 // Reset experiment ids if we received a new valid train name.
1303 resetExperimentIds = true;
1304 }
1305
1306 // Reset if we received a different experiment id.
1307 if (!experimentIdsIn.empty() &&
1308 (trainInfoOnDisk.experimentIds.empty() ||
1309 experimentIdsIn[0] != trainInfoOnDisk.experimentIds[0])) {
1310 resetExperimentIds = true;
1311 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001312 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001313
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001314 // Find the right experiment IDs
1315 std::vector<int64_t> experimentIds;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001316 if (resetExperimentIds || !readTrainInfoSuccess) {
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001317 experimentIds = experimentIdsIn;
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001318 } else {
1319 experimentIds = trainInfoOnDisk.experimentIds;
1320 }
1321
1322 if (!experimentIds.empty()) {
1323 int64_t firstId = experimentIds[0];
1324 switch (state) {
1325 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALL_SUCCESS:
1326 experimentIds.push_back(firstId + 1);
1327 break;
1328 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_INITIATED:
1329 experimentIds.push_back(firstId + 2);
1330 break;
1331 case android::util::BINARY_PUSH_STATE_CHANGED__STATE__INSTALLER_ROLLBACK_SUCCESS:
1332 experimentIds.push_back(firstId + 3);
1333 break;
1334 }
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001335 }
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001336
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001337 // Flatten the experiment IDs to proto
1338 vector<uint8_t> experimentIdsProtoBuffer;
1339 writeExperimentIdsToProto(experimentIds, &experimentIdsProtoBuffer);
Tej Singh9b4a5ec2019-04-25 12:43:35 -07001340 StorageManager::writeTrainInfo(trainVersionCode, trainNameUtf8, state, experimentIds);
Jonathan Nguyenbbe311c2019-03-14 20:44:52 -07001341
1342 userid_t userId = multiuser_get_user_id(uid);
1343 bool requiresStaging = options & IStatsManager::FLAG_REQUIRE_STAGING;
1344 bool rollbackEnabled = options & IStatsManager::FLAG_ROLLBACK_ENABLED;
1345 bool requiresLowLatencyMonitor = options & IStatsManager::FLAG_REQUIRE_LOW_LATENCY_MONITOR;
Muhammad Qureshif4ca8242019-03-01 09:20:15 -08001346 LogEvent event(trainNameUtf8, trainVersionCode, requiresStaging, rollbackEnabled,
1347 requiresLowLatencyMonitor, state, experimentIdsProtoBuffer, userId);
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001348 mProcessor->OnLogEvent(&event);
Jeff Hamiltonfa2f91c2019-03-22 00:25:02 -04001349 return Status::ok();
1350}
1351
1352Status StatsService::getRegisteredExperimentIds(std::vector<int64_t>* experimentIdsOut) {
1353 uid_t uid = IPCThreadState::self()->getCallingUid();
1354
1355 // Caller must be granted these permissions
1356 if (!checkCallingPermission(String16(kPermissionDump))) {
1357 return exception(binder::Status::EX_SECURITY,
1358 StringPrintf("UID %d lacks permission %s", uid, kPermissionDump));
1359 }
1360 if (!checkCallingPermission(String16(kPermissionUsage))) {
1361 return exception(binder::Status::EX_SECURITY,
1362 StringPrintf("UID %d lacks permission %s", uid, kPermissionUsage));
1363 }
1364 // TODO: add verifier permission
1365
1366 // Read the latest train info
1367 InstallTrainInfo trainInfo;
1368 if (!StorageManager::readTrainInfo(trainInfo)) {
1369 // No train info means no experiment IDs, return an empty list
1370 experimentIdsOut->clear();
1371 return Status::ok();
1372 }
1373
1374 // Copy the experiment IDs to the out vector
1375 experimentIdsOut->assign(trainInfo.experimentIds.begin(), trainInfo.experimentIds.end());
Chenjie Yu6b1667c2019-01-18 10:09:33 -08001376 return Status::ok();
1377}
1378
Howard Roa46b6582018-09-18 16:45:02 -07001379hardware::Return<void> StatsService::reportSpeakerImpedance(
1380 const SpeakerImpedance& speakerImpedance) {
Tej Singh8928ed72019-02-22 19:06:22 -08001381 android::util::stats_write(android::util::SPEAKER_IMPEDANCE_REPORTED,
1382 speakerImpedance.speakerLocation, speakerImpedance.milliOhms);
Howard Roa46b6582018-09-18 16:45:02 -07001383
1384 return hardware::Void();
1385}
1386
1387hardware::Return<void> StatsService::reportHardwareFailed(const HardwareFailed& hardwareFailed) {
Tej Singh8928ed72019-02-22 19:06:22 -08001388 android::util::stats_write(android::util::HARDWARE_FAILED, int32_t(hardwareFailed.hardwareType),
1389 hardwareFailed.hardwareLocation, int32_t(hardwareFailed.errorCode));
Howard Roa46b6582018-09-18 16:45:02 -07001390
1391 return hardware::Void();
1392}
1393
1394hardware::Return<void> StatsService::reportPhysicalDropDetected(
1395 const PhysicalDropDetected& physicalDropDetected) {
Tej Singh8928ed72019-02-22 19:06:22 -08001396 android::util::stats_write(android::util::PHYSICAL_DROP_DETECTED,
1397 int32_t(physicalDropDetected.confidencePctg), physicalDropDetected.accelPeak,
1398 physicalDropDetected.freefallDuration);
Howard Roa46b6582018-09-18 16:45:02 -07001399
1400 return hardware::Void();
1401}
1402
1403hardware::Return<void> StatsService::reportChargeCycles(const ChargeCycles& chargeCycles) {
Tej Singh8928ed72019-02-22 19:06:22 -08001404 std::vector<int32_t> buckets = chargeCycles.cycleBucket;
1405 int initialSize = buckets.size();
1406 for (int i = 0; i < 10 - initialSize; i++) {
1407 buckets.push_back(-1); // Push -1 for buckets that do not exist.
1408 }
1409 android::util::stats_write(android::util::CHARGE_CYCLES_REPORTED, buckets[0], buckets[1],
1410 buckets[2], buckets[3], buckets[4], buckets[5], buckets[6], buckets[7], buckets[8],
1411 buckets[9]);
Howard Roa46b6582018-09-18 16:45:02 -07001412
1413 return hardware::Void();
1414}
1415
1416hardware::Return<void> StatsService::reportBatteryHealthSnapshot(
1417 const BatteryHealthSnapshotArgs& batteryHealthSnapshotArgs) {
Tej Singh8928ed72019-02-22 19:06:22 -08001418 android::util::stats_write(android::util::BATTERY_HEALTH_SNAPSHOT,
1419 int32_t(batteryHealthSnapshotArgs.type), batteryHealthSnapshotArgs.temperatureDeciC,
1420 batteryHealthSnapshotArgs.voltageMicroV, batteryHealthSnapshotArgs.currentMicroA,
1421 batteryHealthSnapshotArgs.openCircuitVoltageMicroV,
1422 batteryHealthSnapshotArgs.resistanceMicroOhm, batteryHealthSnapshotArgs.levelPercent);
Howard Roa46b6582018-09-18 16:45:02 -07001423
1424 return hardware::Void();
1425}
1426
1427hardware::Return<void> StatsService::reportSlowIo(const SlowIo& slowIo) {
Tej Singh8928ed72019-02-22 19:06:22 -08001428 android::util::stats_write(android::util::SLOW_IO, int32_t(slowIo.operation), slowIo.count);
Howard Roa46b6582018-09-18 16:45:02 -07001429
1430 return hardware::Void();
1431}
1432
1433hardware::Return<void> StatsService::reportBatteryCausedShutdown(
1434 const BatteryCausedShutdown& batteryCausedShutdown) {
Tej Singh8928ed72019-02-22 19:06:22 -08001435 android::util::stats_write(android::util::BATTERY_CAUSED_SHUTDOWN,
1436 batteryCausedShutdown.voltageMicroV);
Howard Roa46b6582018-09-18 16:45:02 -07001437
1438 return hardware::Void();
1439}
1440
Maggie Whitefc1aa592018-11-28 21:55:23 -08001441hardware::Return<void> StatsService::reportUsbPortOverheatEvent(
1442 const UsbPortOverheatEvent& usbPortOverheatEvent) {
Tej Singh8928ed72019-02-22 19:06:22 -08001443 android::util::stats_write(android::util::USB_PORT_OVERHEAT_EVENT_REPORTED,
1444 usbPortOverheatEvent.plugTemperatureDeciC, usbPortOverheatEvent.maxTemperatureDeciC,
1445 usbPortOverheatEvent.timeToOverheat, usbPortOverheatEvent.timeToHysteresis,
1446 usbPortOverheatEvent.timeToInactive);
Maggie Whitefc1aa592018-11-28 21:55:23 -08001447
1448 return hardware::Void();
1449}
1450
Carter Hsub8fd1e92019-01-11 15:24:45 +08001451hardware::Return<void> StatsService::reportSpeechDspStat(
1452 const SpeechDspStat& speechDspStat) {
Tej Singh8928ed72019-02-22 19:06:22 -08001453 android::util::stats_write(android::util::SPEECH_DSP_STAT_REPORTED,
1454 speechDspStat.totalUptimeMillis, speechDspStat.totalDowntimeMillis,
1455 speechDspStat.totalCrashCount, speechDspStat.totalRecoverCount);
Carter Hsub8fd1e92019-01-11 15:24:45 +08001456
1457 return hardware::Void();
1458}
1459
Maggie White58174da2019-01-18 15:23:35 -08001460hardware::Return<void> StatsService::reportVendorAtom(const VendorAtom& vendorAtom) {
1461 std::string reverseDomainName = (std::string) vendorAtom.reverseDomainName;
1462 if (vendorAtom.atomId < 100000 || vendorAtom.atomId >= 200000) {
1463 ALOGE("Atom ID %ld is not a valid vendor atom ID", (long) vendorAtom.atomId);
1464 return hardware::Void();
1465 }
1466 if (reverseDomainName.length() > 50) {
1467 ALOGE("Vendor atom reverse domain name %s is too long.", reverseDomainName.c_str());
1468 return hardware::Void();
1469 }
1470 LogEvent event(getWallClockSec() * NS_PER_SEC, getElapsedRealtimeNs(), vendorAtom);
1471 mProcessor->OnLogEvent(&event);
1472
1473 return hardware::Void();
1474}
1475
David Chen1d7b0cd2017-11-15 14:20:04 -08001476void StatsService::binderDied(const wp <IBinder>& who) {
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001477 ALOGW("statscompanion service died");
Yangster-mac892f3d32018-05-02 14:16:48 -07001478 StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1479 if (mProcessor != nullptr) {
Howard Roe60992b2018-08-30 14:37:29 -07001480 ALOGW("Reset statsd upon system server restarts.");
Tej Singhf53d4452019-05-09 18:17:59 -07001481 int64_t systemServerRestartNs = getElapsedRealtimeNs();
1482 ProtoOutputStream proto;
1483 mProcessor->WriteActiveConfigsToProtoOutputStream(systemServerRestartNs,
1484 STATSCOMPANION_DIED, &proto);
1485
Olivier Gaillard6c75ecd2019-02-20 09:57:33 +00001486 mProcessor->WriteDataToDisk(STATSCOMPANION_DIED, FAST);
Yangster-mac892f3d32018-05-02 14:16:48 -07001487 mProcessor->resetConfigs();
Tej Singhf53d4452019-05-09 18:17:59 -07001488
1489 std::string serializedActiveConfigs;
1490 if (proto.serializeToString(&serializedActiveConfigs)) {
1491 ActiveConfigList activeConfigs;
1492 if (activeConfigs.ParseFromString(serializedActiveConfigs)) {
1493 mProcessor->SetConfigsActiveState(activeConfigs, systemServerRestartNs);
1494 }
1495 }
Yangster-mac892f3d32018-05-02 14:16:48 -07001496 }
Chenjie Yuaa5b2012018-03-21 13:53:15 -07001497 mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1498 mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
1499 SubscriberReporter::getInstance().setStatsCompanionService(nullptr);
Chenjie Yue2219202018-06-08 10:07:51 -07001500 mPullerManager->SetStatsCompanionService(nullptr);
yro31eb67b2017-10-24 13:33:21 -07001501}
1502
Yao Chenef99c4f2017-09-22 16:26:54 -07001503} // namespace statsd
1504} // namespace os
1505} // namespace android