1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 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 17 #ifndef STATS_SERVICE_H 18 #define STATS_SERVICE_H 19 20 #include <gtest/gtest_prod.h> 21 #include "StatsLogProcessor.h" 22 #include "anomaly/AlarmMonitor.h" 23 #include "config/ConfigManager.h" 24 #include "external/StatsPullerManager.h" 25 #include "logd/LogEventQueue.h" 26 #include "packages/UidMap.h" 27 #include "shell/ShellSubscriber.h" 28 #include "statscompanion_util.h" 29 30 #include <android/frameworks/stats/1.0/IStats.h> 31 #include <android/frameworks/stats/1.0/types.h> 32 #include <android/os/BnStatsManager.h> 33 #include <android/os/IStatsCompanionService.h> 34 #include <android/os/IStatsManager.h> 35 #include <binder/IResultReceiver.h> 36 #include <binder/ParcelFileDescriptor.h> 37 #include <utils/Looper.h> 38 39 #include <deque> 40 #include <mutex> 41 42 using namespace android; 43 using namespace android::base; 44 using namespace android::binder; 45 using namespace android::frameworks::stats::V1_0; 46 using namespace android::os; 47 using namespace std; 48 49 namespace android { 50 namespace os { 51 namespace statsd { 52 53 using android::hardware::Return; 54 55 class StatsService : public BnStatsManager, 56 public IStats, 57 public IBinder::DeathRecipient { 58 public: 59 StatsService(const sp<Looper>& handlerLooper, std::shared_ptr<LogEventQueue> queue); 60 virtual ~StatsService(); 61 62 /** The anomaly alarm registered with AlarmManager won't be updated by less than this. */ 63 const uint32_t MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS = 5; 64 65 virtual status_t onTransact(uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags); 66 virtual status_t dump(int fd, const Vector<String16>& args); 67 virtual status_t command(int inFd, int outFd, int err, Vector<String8>& args, 68 sp<IResultReceiver> resultReceiver); 69 70 virtual Status systemRunning(); 71 virtual Status statsCompanionReady(); 72 virtual Status informAnomalyAlarmFired(); 73 virtual Status informPollAlarmFired(); 74 virtual Status informAlarmForSubscriberTriggeringFired(); 75 76 virtual Status informAllUidData(const ParcelFileDescriptor& fd); 77 virtual Status informOnePackage(const String16& app, int32_t uid, int64_t version, 78 const String16& version_string, const String16& installer); 79 virtual Status informOnePackageRemoved(const String16& app, int32_t uid); 80 virtual Status informDeviceShutdown(); 81 82 /** 83 * Called right before we start processing events. 84 */ 85 void Startup(); 86 87 /** 88 * Called when terminiation signal received. 89 */ 90 void Terminate(); 91 92 /** 93 * Test ONLY interface. In real world, StatsService reads from LogEventQueue. 94 */ 95 virtual void OnLogEvent(LogEvent* event); 96 97 /** 98 * Binder call for clients to request data for this configuration key. 99 */ 100 virtual Status getData(int64_t key, 101 const String16& packageName, 102 vector<uint8_t>* output) override; 103 104 105 /** 106 * Binder call for clients to get metadata across all configs in statsd. 107 */ 108 virtual Status getMetadata(const String16& packageName, 109 vector<uint8_t>* output) override; 110 111 112 /** 113 * Binder call to let clients send a configuration and indicate they're interested when they 114 * should requestData for this configuration. 115 */ 116 virtual Status addConfiguration(int64_t key, 117 const vector<uint8_t>& config, 118 const String16& packageName) override; 119 120 /** 121 * Binder call to let clients register the data fetch operation for a configuration. 122 */ 123 virtual Status setDataFetchOperation(int64_t key, 124 const sp<android::IBinder>& intentSender, 125 const String16& packageName) override; 126 127 /** 128 * Binder call to remove the data fetch operation for the specified config key. 129 */ 130 virtual Status removeDataFetchOperation(int64_t key, 131 const String16& packageName) override; 132 133 /** 134 * Binder call to let clients register the active configs changed operation. 135 */ 136 virtual Status setActiveConfigsChangedOperation(const sp<android::IBinder>& intentSender, 137 const String16& packageName, 138 vector<int64_t>* output) override; 139 140 /** 141 * Binder call to remove the active configs changed operation for the specified package.. 142 */ 143 virtual Status removeActiveConfigsChangedOperation(const String16& packageName) override; 144 /** 145 * Binder call to allow clients to remove the specified configuration. 146 */ 147 virtual Status removeConfiguration(int64_t key, 148 const String16& packageName) override; 149 150 /** 151 * Binder call to associate the given config's subscriberId with the given intentSender. 152 * intentSender must be convertible into an IntentSender (in Java) using IntentSender(IBinder). 153 */ 154 virtual Status setBroadcastSubscriber(int64_t configId, 155 int64_t subscriberId, 156 const sp<android::IBinder>& intentSender, 157 const String16& packageName) override; 158 159 /** 160 * Binder call to unassociate the given config's subscriberId with any intentSender. 161 */ 162 virtual Status unsetBroadcastSubscriber(int64_t configId, 163 int64_t subscriberId, 164 const String16& packageName) override; 165 166 /** Inform statsCompanion that statsd is ready. */ 167 virtual void sayHiToStatsCompanion(); 168 169 /** 170 * Binder call to get AppBreadcrumbReported atom. 171 */ 172 virtual Status sendAppBreadcrumbAtom(int32_t label, int32_t state) override; 173 174 /** 175 * Binder call to register a callback function for a vendor pulled atom. 176 * Note: this atom must NOT have uid as a field. 177 */ 178 virtual Status registerPullerCallback(int32_t atomTag, 179 const sp<android::os::IStatsPullerCallback>& pullerCallback, 180 const String16& packageName) override; 181 182 /** 183 * Binder call to unregister any existing callback function for a vendor pulled atom. 184 */ 185 virtual Status unregisterPullerCallback(int32_t atomTag, const String16& packageName) override; 186 187 /** 188 * Binder call to log BinaryPushStateChanged atom. 189 */ 190 virtual Status sendBinaryPushStateChangedAtom( 191 const android::String16& trainNameIn, 192 const int64_t trainVersionCodeIn, 193 const int options, 194 const int32_t state, 195 const std::vector<int64_t>& experimentIdsIn) override; 196 197 /** 198 * Binder call to log WatchdogRollbackOccurred atom. 199 */ 200 virtual Status sendWatchdogRollbackOccurredAtom( 201 const int32_t rollbackTypeIn, 202 const android::String16& packageNameIn, 203 const int64_t packageVersionCodeIn) override; 204 205 /** 206 * Binder call to get registered experiment IDs. 207 */ 208 virtual Status getRegisteredExperimentIds(std::vector<int64_t>* expIdsOut); 209 210 /** 211 * Binder call to get SpeakerImpedance atom. 212 */ 213 virtual Return<void> reportSpeakerImpedance(const SpeakerImpedance& speakerImpedance) override; 214 215 /** 216 * Binder call to get HardwareFailed atom. 217 */ 218 virtual Return<void> reportHardwareFailed(const HardwareFailed& hardwareFailed) override; 219 220 /** 221 * Binder call to get PhysicalDropDetected atom. 222 */ 223 virtual Return<void> reportPhysicalDropDetected( 224 const PhysicalDropDetected& physicalDropDetected) override; 225 226 /** 227 * Binder call to get ChargeCyclesReported atom. 228 */ 229 virtual Return<void> reportChargeCycles(const ChargeCycles& chargeCycles) override; 230 231 /** 232 * Binder call to get BatteryHealthSnapshot atom. 233 */ 234 virtual Return<void> reportBatteryHealthSnapshot( 235 const BatteryHealthSnapshotArgs& batteryHealthSnapshotArgs) override; 236 237 /** 238 * Binder call to get SlowIo atom. 239 */ 240 virtual Return<void> reportSlowIo(const SlowIo& slowIo) override; 241 242 /** 243 * Binder call to get BatteryCausedShutdown atom. 244 */ 245 virtual Return<void> reportBatteryCausedShutdown( 246 const BatteryCausedShutdown& batteryCausedShutdown) override; 247 248 /** 249 * Binder call to get UsbPortOverheatEvent atom. 250 */ 251 virtual Return<void> reportUsbPortOverheatEvent( 252 const UsbPortOverheatEvent& usbPortOverheatEvent) override; 253 254 /** 255 * Binder call to get Speech DSP state atom. 256 */ 257 virtual Return<void> reportSpeechDspStat( 258 const SpeechDspStat& speechDspStat) override; 259 260 /** 261 * Binder call to get vendor atom. 262 */ 263 virtual Return<void> reportVendorAtom(const VendorAtom& vendorAtom) override; 264 265 /** IBinder::DeathRecipient */ 266 virtual void binderDied(const wp<IBinder>& who) override; 267 268 private: 269 /** 270 * Load system properties at init. 271 */ 272 void init_system_properties(); 273 274 /** 275 * Helper for loading system properties. 276 */ 277 static void init_build_type_callback(void* cookie, const char* name, const char* value, 278 uint32_t serial); 279 280 /** 281 * Proto output of statsd report data dumpsys, wrapped in a StatsDataDumpProto. 282 */ 283 void dumpIncidentSection(int outFd); 284 285 /** 286 * Text or proto output of statsdStats dumpsys. 287 */ 288 void dumpStatsdStats(int outFd, bool verbose, bool proto); 289 290 /** 291 * Print usage information for the commands 292 */ 293 void print_cmd_help(int out); 294 295 /* Runs on its dedicated thread to process pushed stats event from socket. */ 296 void readLogs(); 297 298 /** 299 * Trigger a broadcast. 300 */ 301 status_t cmd_trigger_broadcast(int outFd, Vector<String8>& args); 302 303 304 /** 305 * Trigger an active configs changed broadcast. 306 */ 307 status_t cmd_trigger_active_config_broadcast(int outFd, Vector<String8>& args); 308 309 /** 310 * Handle the config sub-command. 311 */ 312 status_t cmd_config(int inFd, int outFd, int err, Vector<String8>& args); 313 314 /** 315 * Prints some basic stats to std out. 316 */ 317 status_t cmd_print_stats(int outFd, const Vector<String8>& args); 318 319 /** 320 * Print the event log. 321 */ 322 status_t cmd_dump_report(int outFd, const Vector<String8>& args); 323 324 /** 325 * Print the mapping of uids to package names. 326 */ 327 status_t cmd_print_uid_map(int outFd, const Vector<String8>& args); 328 329 /** 330 * Flush the data to disk. 331 */ 332 status_t cmd_write_data_to_disk(int outFd); 333 334 /** 335 * Write an AppBreadcrumbReported event to the StatsLog buffer, as if calling 336 * StatsLog.write(APP_BREADCRUMB_REPORTED). 337 */ 338 status_t cmd_log_app_breadcrumb(int outFd, const Vector<String8>& args); 339 340 /** 341 * Write an BinaryPushStateChanged event, as if calling StatsLog.logBinaryPushStateChanged(). 342 */ 343 status_t cmd_log_binary_push(int outFd, const Vector<String8>& args); 344 345 /** 346 * Print contents of a pulled metrics source. 347 */ 348 status_t cmd_print_pulled_metrics(int outFd, const Vector<String8>& args); 349 350 /** 351 * Removes all configs stored on disk and on memory. 352 */ 353 status_t cmd_remove_all_configs(int outFd); 354 355 /* 356 * Dump memory usage by statsd. 357 */ 358 status_t cmd_dump_memory_info(int outFd); 359 360 /* 361 * Clear all puller cached data 362 */ 363 status_t cmd_clear_puller_cache(int outFd); 364 365 /** 366 * Print all stats logs received to logcat. 367 */ 368 status_t cmd_print_logs(int outFd, const Vector<String8>& args); 369 370 /** 371 * Writes the value of args[uidArgIndex] into uid. 372 * Returns whether the uid is reasonable (type uid_t) and whether 373 * 1. it is equal to the calling uid, or 374 * 2. the device is mEngBuild, or 375 * 3. the caller is AID_ROOT and the uid is AID_SHELL (i.e. ROOT can impersonate SHELL). 376 */ 377 bool getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid); 378 379 /** 380 * Writes the value of uidSting into uid. 381 * Returns whether the uid is reasonable (type uid_t) and whether 382 * 1. it is equal to the calling uid, or 383 * 2. the device is mEngBuild, or 384 * 3. the caller is AID_ROOT and the uid is AID_SHELL (i.e. ROOT can impersonate SHELL). 385 */ 386 bool getUidFromString(const char* uidString, int32_t& uid); 387 388 /** 389 * Adds a configuration after checking permissions and obtaining UID from binder call. 390 */ 391 bool addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config); 392 393 /** 394 * Update a configuration. 395 */ 396 void set_config(int uid, const string& name, const StatsdConfig& config); 397 398 /** 399 * Tracks the uid <--> package name mapping. 400 */ 401 sp<UidMap> mUidMap; 402 403 /** 404 * Fetches external metrics 405 */ 406 sp<StatsPullerManager> mPullerManager; 407 408 /** 409 * Tracks the configurations that have been passed to statsd. 410 */ 411 sp<ConfigManager> mConfigManager; 412 413 /** 414 * The metrics recorder. 415 */ 416 sp<StatsLogProcessor> mProcessor; 417 418 /** 419 * The alarm monitor for anomaly detection. 420 */ 421 const sp<AlarmMonitor> mAnomalyAlarmMonitor; 422 423 /** 424 * The alarm monitor for alarms to directly trigger subscriber. 425 */ 426 const sp<AlarmMonitor> mPeriodicAlarmMonitor; 427 428 /** 429 * Whether this is an eng build. 430 */ 431 bool mEngBuild; 432 433 sp<ShellSubscriber> mShellSubscriber; 434 435 std::shared_ptr<LogEventQueue> mEventQueue; 436 437 FRIEND_TEST(StatsLogProcessorTest, TestActivationsPersistAcrossSystemServerRestart); 438 FRIEND_TEST(StatsServiceTest, TestAddConfig_simple); 439 FRIEND_TEST(StatsServiceTest, TestAddConfig_empty); 440 FRIEND_TEST(StatsServiceTest, TestAddConfig_invalid); 441 FRIEND_TEST(StatsServiceTest, TestGetUidFromArgs); 442 FRIEND_TEST(PartialBucketE2eTest, TestCountMetricNoSplitOnNewApp); 443 FRIEND_TEST(PartialBucketE2eTest, TestCountMetricSplitOnUpgrade); 444 FRIEND_TEST(PartialBucketE2eTest, TestCountMetricSplitOnRemoval); 445 FRIEND_TEST(PartialBucketE2eTest, TestCountMetricWithoutSplit); 446 FRIEND_TEST(PartialBucketE2eTest, TestValueMetricWithoutMinPartialBucket); 447 FRIEND_TEST(PartialBucketE2eTest, TestValueMetricWithMinPartialBucket); 448 FRIEND_TEST(PartialBucketE2eTest, TestGaugeMetricWithoutMinPartialBucket); 449 FRIEND_TEST(PartialBucketE2eTest, TestGaugeMetricWithMinPartialBucket); 450 }; 451 452 } // namespace statsd 453 } // namespace os 454 } // namespace android 455 456 #endif // STATS_SERVICE_H 457