• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #define STATSD_DEBUG false  // STOPSHIP if true
18 #include "Log.h"
19 
20 #include "StatsService.h"
21 #include "stats_log_util.h"
22 #include "android-base/stringprintf.h"
23 #include "config/ConfigKey.h"
24 #include "config/ConfigManager.h"
25 #include "guardrail/StatsdStats.h"
26 #include "storage/StorageManager.h"
27 #include "subscriber/SubscriberReporter.h"
28 
29 #include <android-base/file.h>
30 #include <android-base/strings.h>
31 #include <cutils/multiuser.h>
32 #include <src/statsd_config.pb.h>
33 #include <src/uid_data.pb.h>
34 #include <private/android_filesystem_config.h>
35 #include <statslog_statsd.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <sys/system_properties.h>
39 #include <unistd.h>
40 #include <utils/String16.h>
41 
42 using namespace android;
43 
44 using android::base::StringPrintf;
45 using android::util::FIELD_COUNT_REPEATED;
46 using android::util::FIELD_TYPE_MESSAGE;
47 
48 using Status = ::ndk::ScopedAStatus;
49 
50 namespace android {
51 namespace os {
52 namespace statsd {
53 
54 constexpr const char* kPermissionDump = "android.permission.DUMP";
55 
56 constexpr const char* kPermissionRegisterPullAtom = "android.permission.REGISTER_STATS_PULL_ATOM";
57 
58 constexpr const char* kIncludeCertificateHash = "include_certificate_hash";
59 
60 #define STATS_SERVICE_DIR "/data/misc/stats-service"
61 
62 // for StatsDataDumpProto
63 const int FIELD_ID_REPORTS_LIST = 1;
64 
exception(int32_t code,const std::string & msg)65 static Status exception(int32_t code, const std::string& msg) {
66     ALOGE("%s (%d)", msg.c_str(), code);
67     return Status::fromExceptionCodeWithMessage(code, msg.c_str());
68 }
69 
checkPermission(const char * permission)70 static bool checkPermission(const char* permission) {
71     pid_t pid = AIBinder_getCallingPid();
72     uid_t uid = AIBinder_getCallingUid();
73     return checkPermissionForIds(permission, pid, uid);
74 }
75 
checkUid(uid_t expectedUid)76 Status checkUid(uid_t expectedUid) {
77     uid_t uid = AIBinder_getCallingUid();
78     if (uid == expectedUid || uid == AID_ROOT) {
79         return Status::ok();
80     } else {
81         return exception(EX_SECURITY,
82                          StringPrintf("UID %d is not expected UID %d", uid, expectedUid));
83     }
84 }
85 
86 #define ENFORCE_UID(uid) {                                        \
87     Status status = checkUid((uid));                              \
88     if (!status.isOk()) {                                         \
89         return status;                                            \
90     }                                                             \
91 }
92 
StatsService(const sp<Looper> & handlerLooper,shared_ptr<LogEventQueue> queue)93 StatsService::StatsService(const sp<Looper>& handlerLooper, shared_ptr<LogEventQueue> queue)
94     : mAnomalyAlarmMonitor(new AlarmMonitor(
95               MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
96               [this](const shared_ptr<IStatsCompanionService>& /*sc*/, int64_t timeMillis) {
97                   mProcessor->setAnomalyAlarm(timeMillis);
98                   StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
99               },
__anon7d48030d0202(const shared_ptr<IStatsCompanionService>& ) 100               [this](const shared_ptr<IStatsCompanionService>& /*sc*/) {
101                   mProcessor->cancelAnomalyAlarm();
102                   StatsdStats::getInstance().noteRegisteredAnomalyAlarmChanged();
103               })),
104       mPeriodicAlarmMonitor(new AlarmMonitor(
105               MIN_DIFF_TO_UPDATE_REGISTERED_ALARM_SECS,
__anon7d48030d0302(const shared_ptr<IStatsCompanionService>& sc, int64_t timeMillis) 106               [](const shared_ptr<IStatsCompanionService>& sc, int64_t timeMillis) {
107                   if (sc != nullptr) {
108                       sc->setAlarmForSubscriberTriggering(timeMillis);
109                       StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
110                   }
111               },
__anon7d48030d0402(const shared_ptr<IStatsCompanionService>& sc) 112               [](const shared_ptr<IStatsCompanionService>& sc) {
113                   if (sc != nullptr) {
114                       sc->cancelAlarmForSubscriberTriggering();
115                       StatsdStats::getInstance().noteRegisteredPeriodicAlarmChanged();
116                   }
117               })),
118       mEventQueue(queue),
119       mBootCompleteTrigger({kBootCompleteTag, kUidMapReceivedTag, kAllPullersRegisteredTag},
__anon7d48030d0502() 120                            [this]() { mProcessor->onStatsdInitCompleted(getElapsedRealtimeNs()); }),
121       mStatsCompanionServiceDeathRecipient(
122               AIBinder_DeathRecipient_new(StatsService::statsCompanionServiceDied)) {
123     mUidMap = UidMap::getInstance();
124     mPullerManager = new StatsPullerManager();
125     StatsPuller::SetUidMap(mUidMap);
126     mConfigManager = new ConfigManager();
127     mProcessor = new StatsLogProcessor(
128             mUidMap, mPullerManager, mAnomalyAlarmMonitor, mPeriodicAlarmMonitor,
129             getElapsedRealtimeNs(),
__anon7d48030d0602(const ConfigKey& key) 130             [this](const ConfigKey& key) {
131                 shared_ptr<IPendingIntentRef> receiver = mConfigManager->GetConfigReceiver(key);
132                 if (receiver == nullptr) {
133                     VLOG("Could not find a broadcast receiver for %s", key.ToString().c_str());
134                     return false;
135                 }
136                 Status status = receiver->sendDataBroadcast(mProcessor->getLastReportTimeNs(key));
137                 if (status.isOk()) {
138                     return true;
139                 }
140                 if (status.getExceptionCode() == EX_TRANSACTION_FAILED &&
141                     status.getStatus() == STATUS_DEAD_OBJECT) {
142                     mConfigManager->RemoveConfigReceiver(key, receiver);
143                 }
144                 VLOG("Failed to send a broadcast for receiver %s", key.ToString().c_str());
145                 return false;
146             },
__anon7d48030d0702(const int& uid, const vector<int64_t>& activeConfigs) 147             [this](const int& uid, const vector<int64_t>& activeConfigs) {
148                 shared_ptr<IPendingIntentRef> receiver =
149                     mConfigManager->GetActiveConfigsChangedReceiver(uid);
150                 if (receiver == nullptr) {
151                     VLOG("Could not find receiver for uid %d", uid);
152                     return false;
153                 }
154                 Status status = receiver->sendActiveConfigsChangedBroadcast(activeConfigs);
155                 if (status.isOk()) {
156                     VLOG("StatsService::active configs broadcast succeeded for uid %d" , uid);
157                     return true;
158                 }
159                 if (status.getExceptionCode() == EX_TRANSACTION_FAILED &&
160                     status.getStatus() == STATUS_DEAD_OBJECT) {
161                     mConfigManager->RemoveActiveConfigsChangedReceiver(uid, receiver);
162                 }
163                 VLOG("StatsService::active configs broadcast failed for uid %d", uid);
164                 return false;
165             });
166 
167     mUidMap->setListener(mProcessor);
168     mConfigManager->AddListener(mProcessor);
169 
170     init_system_properties();
171 
172     if (mEventQueue != nullptr) {
__anon7d48030d0802null173         std::thread pushedEventThread([this] { readLogs(); });
174         pushedEventThread.detach();
175     }
176 }
177 
~StatsService()178 StatsService::~StatsService() {
179 }
180 
181 /* Runs on a dedicated thread to process pushed events. */
readLogs()182 void StatsService::readLogs() {
183     // Read forever..... long live statsd
184     while (1) {
185         // Block until an event is available.
186         auto event = mEventQueue->waitPop();
187         // Pass it to StatsLogProcess to all configs/metrics
188         // At this point, the LogEventQueue is not blocked, so that the socketListener
189         // can read events from the socket and write to buffer to avoid data drop.
190         mProcessor->OnLogEvent(event.get());
191         // The ShellSubscriber is only used by shell for local debugging.
192         if (mShellSubscriber != nullptr) {
193             mShellSubscriber->onLogEvent(*event);
194         }
195     }
196 }
197 
init_system_properties()198 void StatsService::init_system_properties() {
199     mEngBuild = false;
200     const prop_info* buildType = __system_property_find("ro.build.type");
201     if (buildType != NULL) {
202         __system_property_read_callback(buildType, init_build_type_callback, this);
203     }
204 }
205 
init_build_type_callback(void * cookie,const char *,const char * value,uint32_t serial)206 void StatsService::init_build_type_callback(void* cookie, const char* /*name*/, const char* value,
207                                             uint32_t serial) {
208     if (0 == strcmp("eng", value) || 0 == strcmp("userdebug", value)) {
209         reinterpret_cast<StatsService*>(cookie)->mEngBuild = true;
210     }
211 }
212 
213 /**
214  * Write data from statsd.
215  * Format for statsdStats:  adb shell dumpsys stats --metadata [-v] [--proto]
216  * Format for data report:  adb shell dumpsys stats [anything other than --metadata] [--proto]
217  * Anything ending in --proto will be in proto format.
218  * Anything without --metadata as the first argument will be report information.
219  *     (bugreports call "adb shell dumpsys stats --dump-priority NORMAL -a --proto")
220  * TODO: Come up with a more robust method of enacting <serviceutils/PriorityDumper.h>.
221  */
dump(int fd,const char ** args,uint32_t numArgs)222 status_t StatsService::dump(int fd, const char** args, uint32_t numArgs) {
223     if (!checkPermission(kPermissionDump)) {
224         return PERMISSION_DENIED;
225     }
226 
227     int lastArg = numArgs - 1;
228     bool asProto = false;
229     if (lastArg >= 0 && string(args[lastArg]) == "--proto") { // last argument
230         asProto = true;
231         lastArg--;
232     }
233     if (numArgs > 0 && string(args[0]) == "--metadata") { // first argument
234         // Request is to dump statsd stats.
235         bool verbose = false;
236         if (lastArg >= 0 && string(args[lastArg]) == "-v") {
237             verbose = true;
238             lastArg--;
239         }
240         dumpStatsdStats(fd, verbose, asProto);
241     } else {
242         // Request is to dump statsd report data.
243         if (asProto) {
244             dumpIncidentSection(fd);
245         } else {
246             dprintf(fd, "Non-proto format of stats data dump not available; see proto version.\n");
247         }
248     }
249 
250     return NO_ERROR;
251 }
252 
253 /**
254  * Write debugging data about statsd in text or proto format.
255  */
dumpStatsdStats(int out,bool verbose,bool proto)256 void StatsService::dumpStatsdStats(int out, bool verbose, bool proto) {
257     if (proto) {
258         vector<uint8_t> data;
259         StatsdStats::getInstance().dumpStats(&data, false); // does not reset statsdStats.
260         for (size_t i = 0; i < data.size(); i ++) {
261             dprintf(out, "%c", data[i]);
262         }
263     } else {
264         StatsdStats::getInstance().dumpStats(out);
265         mProcessor->dumpStates(out, verbose);
266     }
267 }
268 
269 /**
270  * Write stats report data in StatsDataDumpProto incident section format.
271  */
dumpIncidentSection(int out)272 void StatsService::dumpIncidentSection(int out) {
273     ProtoOutputStream proto;
274     for (const ConfigKey& configKey : mConfigManager->GetAllConfigKeys()) {
275         uint64_t reportsListToken =
276                 proto.start(FIELD_TYPE_MESSAGE | FIELD_COUNT_REPEATED | FIELD_ID_REPORTS_LIST);
277         // Don't include the current bucket to avoid skipping buckets.
278         // If we need to include the current bucket later, consider changing to NO_TIME_CONSTRAINTS
279         // or other alternatives to avoid skipping buckets for pulled metrics.
280         mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), getWallClockNs(),
281                                  false /* includeCurrentBucket */, false /* erase_data */, ADB_DUMP,
282                                  FAST, &proto);
283         proto.end(reportsListToken);
284         proto.flush(out);
285         proto.clear();
286     }
287 }
288 
289 /**
290  * Implementation of the adb shell cmd stats command.
291  */
handleShellCommand(int in,int out,int err,const char ** argv,uint32_t argc)292 status_t StatsService::handleShellCommand(int in, int out, int err, const char** argv,
293                                           uint32_t argc) {
294     uid_t uid = AIBinder_getCallingUid();
295     if (uid != AID_ROOT && uid != AID_SHELL) {
296         return PERMISSION_DENIED;
297     }
298 
299     Vector<String8> utf8Args;
300     utf8Args.setCapacity(argc);
301     for (uint32_t i = 0; i < argc; i++) {
302         utf8Args.push(String8(argv[i]));
303     }
304 
305     if (argc >= 1) {
306         // adb shell cmd stats config ...
307         if (!utf8Args[0].compare(String8("config"))) {
308             return cmd_config(in, out, err, utf8Args);
309         }
310 
311         if (!utf8Args[0].compare(String8("print-uid-map"))) {
312             return cmd_print_uid_map(out, utf8Args);
313         }
314 
315         if (!utf8Args[0].compare(String8("dump-report"))) {
316             return cmd_dump_report(out, utf8Args);
317         }
318 
319         if (!utf8Args[0].compare(String8("pull-source")) && argc > 1) {
320             return cmd_print_pulled_metrics(out, utf8Args);
321         }
322 
323         if (!utf8Args[0].compare(String8("send-broadcast"))) {
324             return cmd_trigger_broadcast(out, utf8Args);
325         }
326 
327         if (!utf8Args[0].compare(String8("print-stats"))) {
328             return cmd_print_stats(out, utf8Args);
329         }
330 
331         if (!utf8Args[0].compare(String8("meminfo"))) {
332             return cmd_dump_memory_info(out);
333         }
334 
335         if (!utf8Args[0].compare(String8("write-to-disk"))) {
336             return cmd_write_data_to_disk(out);
337         }
338 
339         if (!utf8Args[0].compare(String8("log-app-breadcrumb"))) {
340             return cmd_log_app_breadcrumb(out, utf8Args);
341         }
342 
343         if (!utf8Args[0].compare(String8("log-binary-push"))) {
344             return cmd_log_binary_push(out, utf8Args);
345         }
346 
347         if (!utf8Args[0].compare(String8("clear-puller-cache"))) {
348             return cmd_clear_puller_cache(out);
349         }
350 
351         if (!utf8Args[0].compare(String8("print-logs"))) {
352             return cmd_print_logs(out, utf8Args);
353         }
354 
355         if (!utf8Args[0].compare(String8("send-active-configs"))) {
356             return cmd_trigger_active_config_broadcast(out, utf8Args);
357         }
358 
359         if (!utf8Args[0].compare(String8("data-subscribe"))) {
360             {
361                 std::lock_guard<std::mutex> lock(mShellSubscriberMutex);
362                 if (mShellSubscriber == nullptr) {
363                     mShellSubscriber = new ShellSubscriber(mUidMap, mPullerManager);
364                 }
365             }
366             int timeoutSec = -1;
367             if (argc >= 2) {
368                 timeoutSec = atoi(utf8Args[1].c_str());
369             }
370             mShellSubscriber->startNewSubscription(in, out, timeoutSec);
371             return NO_ERROR;
372         }
373     }
374 
375     print_cmd_help(out);
376     return NO_ERROR;
377 }
378 
print_cmd_help(int out)379 void StatsService::print_cmd_help(int out) {
380     dprintf(out,
381             "usage: adb shell cmd stats print-stats-log [tag_required] "
382             "[timestamp_nsec_optional]\n");
383     dprintf(out, "\n");
384     dprintf(out, "\n");
385     dprintf(out, "usage: adb shell cmd stats meminfo\n");
386     dprintf(out, "\n");
387     dprintf(out, "  Prints the malloc debug information. You need to run the following first: \n");
388     dprintf(out, "   # adb shell stop\n");
389     dprintf(out, "   # adb shell setprop libc.debug.malloc.program statsd \n");
390     dprintf(out, "   # adb shell setprop libc.debug.malloc.options backtrace \n");
391     dprintf(out, "   # adb shell start\n");
392     dprintf(out, "\n");
393     dprintf(out, "\n");
394     dprintf(out, "usage: adb shell cmd stats print-uid-map [PKG]\n");
395     dprintf(out, "usage: adb shell cmd stats print-uid-map --with_certificate_hash\n");
396     dprintf(out, "\n");
397     dprintf(out, "  Prints the UID, app name, version mapping.\n");
398     dprintf(out,
399             "  PKG                         Optional package name to print the uids of the "
400             "package\n");
401     dprintf(out, "  --with_certificate_hash     Print package certificate hash in hex\n");
402     dprintf(out, "\n");
403     dprintf(out, "\n");
404     dprintf(out, "usage: adb shell cmd stats pull-source ATOM_TAG [PACKAGE] \n");
405     dprintf(out, "\n");
406     dprintf(out, "  Prints the output of a pulled atom\n");
407     dprintf(out, "  UID           The atom to pull\n");
408     dprintf(out, "  PACKAGE       The package to pull from. Default is AID_SYSTEM\n");
409     dprintf(out, "\n");
410     dprintf(out, "\n");
411     dprintf(out, "usage: adb shell cmd stats write-to-disk \n");
412     dprintf(out, "\n");
413     dprintf(out, "  Flushes all data on memory to disk.\n");
414     dprintf(out, "\n");
415     dprintf(out, "\n");
416     dprintf(out, "usage: adb shell cmd stats log-app-breadcrumb [UID] LABEL STATE\n");
417     dprintf(out, "  Writes an AppBreadcrumbReported event to the statslog buffer.\n");
418     dprintf(out, "  UID           The uid to use. It is only possible to pass a UID\n");
419     dprintf(out, "                parameter on eng builds. If UID is omitted the calling\n");
420     dprintf(out, "                uid is used.\n");
421     dprintf(out, "  LABEL         Integer in [0, 15], as per atoms.proto.\n");
422     dprintf(out, "  STATE         Integer in [0, 3], as per atoms.proto.\n");
423     dprintf(out, "\n");
424     dprintf(out, "\n");
425     dprintf(out,
426             "usage: adb shell cmd stats log-binary-push NAME VERSION STAGING ROLLBACK_ENABLED "
427             "LOW_LATENCY STATE EXPERIMENT_IDS\n");
428     dprintf(out, "  Log a binary push state changed event.\n");
429     dprintf(out, "  NAME                The train name.\n");
430     dprintf(out, "  VERSION             The train version code.\n");
431     dprintf(out, "  STAGING             If this train requires a restart.\n");
432     dprintf(out, "  ROLLBACK_ENABLED    If rollback should be enabled for this install.\n");
433     dprintf(out, "  LOW_LATENCY         If the train requires low latency monitoring.\n");
434     dprintf(out, "  STATE               The status of the train push.\n");
435     dprintf(out, "                      Integer value of the enum in atoms.proto.\n");
436     dprintf(out, "  EXPERIMENT_IDS      Comma separated list of experiment ids.\n");
437     dprintf(out, "                      Leave blank for none.\n");
438     dprintf(out, "\n");
439     dprintf(out, "\n");
440     dprintf(out, "usage: adb shell cmd stats config remove [UID] [NAME]\n");
441     dprintf(out, "usage: adb shell cmd stats config update [UID] NAME\n");
442     dprintf(out, "\n");
443     dprintf(out, "  Adds, updates or removes a configuration. The proto should be in\n");
444     dprintf(out, "  wire-encoded protobuf format and passed via stdin. If no UID and name is\n");
445     dprintf(out, "  provided, then all configs will be removed from memory and disk.\n");
446     dprintf(out, "\n");
447     dprintf(out, "  UID           The uid to use. It is only possible to pass the UID\n");
448     dprintf(out, "                parameter on eng builds. If UID is omitted the calling\n");
449     dprintf(out, "                uid is used.\n");
450     dprintf(out, "  NAME          The per-uid name to use\n");
451     dprintf(out, "\n");
452     dprintf(out, "\n              *Note: If both UID and NAME are omitted then all configs will\n");
453     dprintf(out, "\n                     be removed from memory and disk!\n");
454     dprintf(out, "\n");
455     dprintf(out,
456             "usage: adb shell cmd stats dump-report [UID] NAME [--keep_data] "
457             "[--include_current_bucket] [--proto]\n");
458     dprintf(out, "  Dump all metric data for a configuration.\n");
459     dprintf(out, "  UID           The uid of the configuration. It is only possible to pass\n");
460     dprintf(out, "                the UID parameter on eng builds. If UID is omitted the\n");
461     dprintf(out, "                calling uid is used.\n");
462     dprintf(out, "  NAME          The name of the configuration\n");
463     dprintf(out, "  --keep_data   Do NOT erase the data upon dumping it.\n");
464     dprintf(out, "  --proto       Print proto binary.\n");
465     dprintf(out, "\n");
466     dprintf(out, "\n");
467     dprintf(out, "usage: adb shell cmd stats send-broadcast [UID] NAME\n");
468     dprintf(out, "  Send a broadcast that triggers the subscriber to fetch metrics.\n");
469     dprintf(out, "  UID           The uid of the configuration. It is only possible to pass\n");
470     dprintf(out, "                the UID parameter on eng builds. If UID is omitted the\n");
471     dprintf(out, "                calling uid is used.\n");
472     dprintf(out, "  NAME          The name of the configuration\n");
473     dprintf(out, "\n");
474     dprintf(out, "\n");
475     dprintf(out,
476             "usage: adb shell cmd stats send-active-configs [--uid=UID] [--configs] "
477             "[NAME1] [NAME2] [NAME3..]\n");
478     dprintf(out, "  Send a broadcast that informs the subscriber of the current active configs.\n");
479     dprintf(out, "  --uid=UID     The uid of the configurations. It is only possible to pass\n");
480     dprintf(out, "                the UID parameter on eng builds. If UID is omitted the\n");
481     dprintf(out, "                calling uid is used.\n");
482     dprintf(out, "  --configs     Send the list of configs in the name list instead of\n");
483     dprintf(out, "                the currently active configs\n");
484     dprintf(out, "  NAME LIST     List of configuration names to be included in the broadcast.\n");
485     dprintf(out, "\n");
486     dprintf(out, "\n");
487     dprintf(out, "usage: adb shell cmd stats print-stats\n");
488     dprintf(out, "  Prints some basic stats.\n");
489     dprintf(out, "  --proto       Print proto binary instead of string format.\n");
490     dprintf(out, "\n");
491     dprintf(out, "\n");
492     dprintf(out, "usage: adb shell cmd stats clear-puller-cache\n");
493     dprintf(out, "  Clear cached puller data.\n");
494     dprintf(out, "\n");
495     dprintf(out, "usage: adb shell cmd stats print-logs\n");
496     dprintf(out, "  Requires root privileges.\n");
497     dprintf(out, "  Can be disabled by calling adb shell cmd stats print-logs 0\n");
498 }
499 
cmd_trigger_broadcast(int out,Vector<String8> & args)500 status_t StatsService::cmd_trigger_broadcast(int out, Vector<String8>& args) {
501     string name;
502     bool good = false;
503     int uid;
504     const int argCount = args.size();
505     if (argCount == 2) {
506         // Automatically pick the UID
507         uid = AIBinder_getCallingUid();
508         name.assign(args[1].c_str(), args[1].size());
509         good = true;
510     } else if (argCount == 3) {
511         good = getUidFromArgs(args, 1, uid);
512         if (!good) {
513             dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
514                          "other UIDs on eng or userdebug builds.\n");
515         }
516         name.assign(args[2].c_str(), args[2].size());
517     }
518     if (!good) {
519         print_cmd_help(out);
520         return UNKNOWN_ERROR;
521     }
522     ConfigKey key(uid, StrToInt64(name));
523     shared_ptr<IPendingIntentRef> receiver = mConfigManager->GetConfigReceiver(key);
524     if (receiver == nullptr) {
525         VLOG("Could not find receiver for %s, %s", args[1].c_str(), args[2].c_str());
526         return UNKNOWN_ERROR;
527     } else if (receiver->sendDataBroadcast(mProcessor->getLastReportTimeNs(key)).isOk()) {
528         VLOG("StatsService::trigger broadcast succeeded to %s, %s", args[1].c_str(),
529              args[2].c_str());
530     } else {
531         VLOG("StatsService::trigger broadcast failed to %s, %s", args[1].c_str(), args[2].c_str());
532         return UNKNOWN_ERROR;
533     }
534     return NO_ERROR;
535 }
536 
cmd_trigger_active_config_broadcast(int out,Vector<String8> & args)537 status_t StatsService::cmd_trigger_active_config_broadcast(int out, Vector<String8>& args) {
538     const int argCount = args.size();
539     int uid;
540     vector<int64_t> configIds;
541     if (argCount == 1) {
542         // Automatically pick the uid and send a broadcast that has no active configs.
543         uid = AIBinder_getCallingUid();
544         mProcessor->GetActiveConfigs(uid, configIds);
545     } else {
546         int curArg = 1;
547         if(args[curArg].find("--uid=") == 0) {
548             string uidArgStr(args[curArg].c_str());
549             string uidStr = uidArgStr.substr(6);
550             if (!getUidFromString(uidStr.c_str(), uid)) {
551                 dprintf(out, "Invalid UID. Note that the config can only be set for "
552                              "other UIDs on eng or userdebug builds.\n");
553                 return UNKNOWN_ERROR;
554             }
555             curArg++;
556         } else {
557             uid = AIBinder_getCallingUid();
558         }
559         if (curArg == argCount || args[curArg] != "--configs") {
560             VLOG("Reached end of args, or specify configs not set. Sending actual active configs,");
561             mProcessor->GetActiveConfigs(uid, configIds);
562         } else {
563             // Flag specified, use the given list of configs.
564             curArg++;
565             for (int i = curArg; i < argCount; i++) {
566                 char* endp;
567                 int64_t configID = strtoll(args[i].c_str(), &endp, 10);
568                 if (endp == args[i].c_str() || *endp != '\0') {
569                     dprintf(out, "Error parsing config ID.\n");
570                     return UNKNOWN_ERROR;
571                 }
572                 VLOG("Adding config id %ld", static_cast<long>(configID));
573                 configIds.push_back(configID);
574             }
575         }
576     }
577     shared_ptr<IPendingIntentRef> receiver = mConfigManager->GetActiveConfigsChangedReceiver(uid);
578     if (receiver == nullptr) {
579         VLOG("Could not find receiver for uid %d", uid);
580         return UNKNOWN_ERROR;
581     } else if (receiver->sendActiveConfigsChangedBroadcast(configIds).isOk()) {
582         VLOG("StatsService::trigger active configs changed broadcast succeeded for uid %d" , uid);
583     } else {
584         VLOG("StatsService::trigger active configs changed broadcast failed for uid %d", uid);
585         return UNKNOWN_ERROR;
586     }
587     return NO_ERROR;
588 }
589 
cmd_config(int in,int out,int err,Vector<String8> & args)590 status_t StatsService::cmd_config(int in, int out, int err, Vector<String8>& args) {
591     const int argCount = args.size();
592     if (argCount >= 2) {
593         if (args[1] == "update" || args[1] == "remove") {
594             bool good = false;
595             int uid = -1;
596             string name;
597 
598             if (argCount == 3) {
599                 // Automatically pick the UID
600                 uid = AIBinder_getCallingUid();
601                 name.assign(args[2].c_str(), args[2].size());
602                 good = true;
603             } else if (argCount == 4) {
604                 good = getUidFromArgs(args, 2, uid);
605                 if (!good) {
606                     dprintf(err, "Invalid UID. Note that the config can only be set for "
607                                  "other UIDs on eng or userdebug builds.\n");
608                 }
609                 name.assign(args[3].c_str(), args[3].size());
610             } else if (argCount == 2 && args[1] == "remove") {
611                 good = true;
612             }
613 
614             if (!good) {
615                 // If arg parsing failed, print the help text and return an error.
616                 print_cmd_help(out);
617                 return UNKNOWN_ERROR;
618             }
619 
620             if (args[1] == "update") {
621                 char* endp;
622                 int64_t configID = strtoll(name.c_str(), &endp, 10);
623                 if (endp == name.c_str() || *endp != '\0') {
624                     dprintf(err, "Error parsing config ID.\n");
625                     return UNKNOWN_ERROR;
626                 }
627 
628                 // Read stream into buffer.
629                 string buffer;
630                 if (!android::base::ReadFdToString(in, &buffer)) {
631                     dprintf(err, "Error reading stream for StatsConfig.\n");
632                     return UNKNOWN_ERROR;
633                 }
634 
635                 // Parse buffer.
636                 StatsdConfig config;
637                 if (!config.ParseFromString(buffer)) {
638                     dprintf(err, "Error parsing proto stream for StatsConfig.\n");
639                     return UNKNOWN_ERROR;
640                 }
641 
642                 // Add / update the config.
643                 mConfigManager->UpdateConfig(ConfigKey(uid, configID), config);
644             } else {
645                 if (argCount == 2) {
646                     cmd_remove_all_configs(out);
647                 } else {
648                     // Remove the config.
649                     mConfigManager->RemoveConfig(ConfigKey(uid, StrToInt64(name)));
650                 }
651             }
652 
653             return NO_ERROR;
654         }
655     }
656     print_cmd_help(out);
657     return UNKNOWN_ERROR;
658 }
659 
cmd_dump_report(int out,const Vector<String8> & args)660 status_t StatsService::cmd_dump_report(int out, const Vector<String8>& args) {
661     if (mProcessor != nullptr) {
662         int argCount = args.size();
663         bool good = false;
664         bool proto = false;
665         bool includeCurrentBucket = false;
666         bool eraseData = true;
667         int uid;
668         string name;
669         if (!std::strcmp("--proto", args[argCount-1].c_str())) {
670             proto = true;
671             argCount -= 1;
672         }
673         if (!std::strcmp("--include_current_bucket", args[argCount-1].c_str())) {
674             includeCurrentBucket = true;
675             argCount -= 1;
676         }
677         if (!std::strcmp("--keep_data", args[argCount-1].c_str())) {
678             eraseData = false;
679             argCount -= 1;
680         }
681         if (argCount == 2) {
682             // Automatically pick the UID
683             uid = AIBinder_getCallingUid();
684             name.assign(args[1].c_str(), args[1].size());
685             good = true;
686         } else if (argCount == 3) {
687             good = getUidFromArgs(args, 1, uid);
688             if (!good) {
689                 dprintf(out, "Invalid UID. Note that the metrics can only be dumped for "
690                              "other UIDs on eng or userdebug builds.\n");
691             }
692             name.assign(args[2].c_str(), args[2].size());
693         }
694         if (good) {
695             vector<uint8_t> data;
696             mProcessor->onDumpReport(ConfigKey(uid, StrToInt64(name)), getElapsedRealtimeNs(),
697                                      getWallClockNs(), includeCurrentBucket, eraseData, ADB_DUMP,
698                                      NO_TIME_CONSTRAINTS, &data);
699             if (proto) {
700                 for (size_t i = 0; i < data.size(); i ++) {
701                     dprintf(out, "%c", data[i]);
702                 }
703             } else {
704                 dprintf(out, "Non-proto stats data dump not currently supported.\n");
705             }
706             return android::OK;
707         } else {
708             // If arg parsing failed, print the help text and return an error.
709             print_cmd_help(out);
710             return UNKNOWN_ERROR;
711         }
712     } else {
713         dprintf(out, "Log processor does not exist...\n");
714         return UNKNOWN_ERROR;
715     }
716 }
717 
cmd_print_stats(int out,const Vector<String8> & args)718 status_t StatsService::cmd_print_stats(int out, const Vector<String8>& args) {
719     int argCount = args.size();
720     bool proto = false;
721     if (!std::strcmp("--proto", args[argCount-1].c_str())) {
722         proto = true;
723         argCount -= 1;
724     }
725     StatsdStats& statsdStats = StatsdStats::getInstance();
726     if (proto) {
727         vector<uint8_t> data;
728         statsdStats.dumpStats(&data, false); // does not reset statsdStats.
729         for (size_t i = 0; i < data.size(); i ++) {
730             dprintf(out, "%c", data[i]);
731         }
732 
733     } else {
734         vector<ConfigKey> configs = mConfigManager->GetAllConfigKeys();
735         for (const ConfigKey& key : configs) {
736             dprintf(out, "Config %s uses %zu bytes\n", key.ToString().c_str(),
737                     mProcessor->GetMetricsSize(key));
738         }
739         statsdStats.dumpStats(out);
740     }
741     return NO_ERROR;
742 }
743 
cmd_print_uid_map(int out,const Vector<String8> & args)744 status_t StatsService::cmd_print_uid_map(int out, const Vector<String8>& args) {
745     if (args.size() > 1) {
746         if (!std::strcmp("--with_certificate_hash", args[1].c_str())) {
747             mUidMap->printUidMap(out, /* includeCertificateHash */ true);
748         } else {
749             string pkg;
750             pkg.assign(args[1].c_str(), args[1].size());
751             auto uids = mUidMap->getAppUid(pkg);
752             dprintf(out, "%s -> [ ", pkg.c_str());
753             for (const auto& uid : uids) {
754                 dprintf(out, "%d ", uid);
755             }
756             dprintf(out, "]\n");
757         }
758     } else {
759         mUidMap->printUidMap(out, /* includeCertificateHash */ false);
760     }
761     return NO_ERROR;
762 }
763 
cmd_write_data_to_disk(int out)764 status_t StatsService::cmd_write_data_to_disk(int out) {
765     dprintf(out, "Writing data to disk\n");
766     mProcessor->WriteDataToDisk(ADB_DUMP, NO_TIME_CONSTRAINTS, getElapsedRealtimeNs(),
767                                 getWallClockNs());
768     return NO_ERROR;
769 }
770 
cmd_log_app_breadcrumb(int out,const Vector<String8> & args)771 status_t StatsService::cmd_log_app_breadcrumb(int out, const Vector<String8>& args) {
772     bool good = false;
773     int32_t uid;
774     int32_t label;
775     int32_t state;
776     const int argCount = args.size();
777     if (argCount == 3) {
778         // Automatically pick the UID
779         uid = AIBinder_getCallingUid();
780         label = atoi(args[1].c_str());
781         state = atoi(args[2].c_str());
782         good = true;
783     } else if (argCount == 4) {
784         good = getUidFromArgs(args, 1, uid);
785         if (!good) {
786             dprintf(out,
787                     "Invalid UID. Note that selecting a UID for writing AppBreadcrumb can only be "
788                     "done for other UIDs on eng or userdebug builds.\n");
789         }
790         label = atoi(args[2].c_str());
791         state = atoi(args[3].c_str());
792     }
793     if (good) {
794         dprintf(out, "Logging AppBreadcrumbReported(%d, %d, %d) to statslog.\n", uid, label, state);
795         android::os::statsd::util::stats_write(
796                 android::os::statsd::util::APP_BREADCRUMB_REPORTED, uid, label, state);
797     } else {
798         print_cmd_help(out);
799         return UNKNOWN_ERROR;
800     }
801     return NO_ERROR;
802 }
803 
cmd_log_binary_push(int out,const Vector<String8> & args)804 status_t StatsService::cmd_log_binary_push(int out, const Vector<String8>& args) {
805     // Security checks are done in the sendBinaryPushStateChanged atom.
806     const int argCount = args.size();
807     if (argCount != 7 && argCount != 8) {
808         dprintf(out, "Incorrect number of argument supplied\n");
809         return UNKNOWN_ERROR;
810     }
811     string trainName = string(args[1].c_str());
812     int64_t trainVersion = strtoll(args[2].c_str(), nullptr, 10);
813     int32_t state = atoi(args[6].c_str());
814     vector<int64_t> experimentIds;
815     if (argCount == 8) {
816         vector<string> experimentIdsString = android::base::Split(string(args[7].c_str()), ",");
817         for (string experimentIdString : experimentIdsString) {
818             int64_t experimentId = strtoll(experimentIdString.c_str(), nullptr, 10);
819             experimentIds.push_back(experimentId);
820         }
821     }
822     dprintf(out, "Logging BinaryPushStateChanged\n");
823     vector<uint8_t> experimentIdBytes;
824     writeExperimentIdsToProto(experimentIds, &experimentIdBytes);
825     LogEvent event(trainName, trainVersion, args[3], args[4], args[5], state, experimentIdBytes, 0);
826     mProcessor->OnLogEvent(&event);
827     return NO_ERROR;
828 }
829 
cmd_print_pulled_metrics(int out,const Vector<String8> & args)830 status_t StatsService::cmd_print_pulled_metrics(int out, const Vector<String8>& args) {
831     int s = atoi(args[1].c_str());
832     vector<int32_t> uids;
833     if (args.size() > 2) {
834         string package = string(args[2].c_str());
835         auto it = UidMap::sAidToUidMapping.find(package);
836         if (it != UidMap::sAidToUidMapping.end()) {
837             uids.push_back(it->second);
838         } else {
839             set<int32_t> uids_set = mUidMap->getAppUid(package);
840             uids.insert(uids.end(), uids_set.begin(), uids_set.end());
841         }
842     } else {
843         uids.push_back(AID_SYSTEM);
844     }
845     vector<shared_ptr<LogEvent>> stats;
846     if (mPullerManager->Pull(s, uids, getElapsedRealtimeNs(), &stats)) {
847         for (const auto& it : stats) {
848             dprintf(out, "Pull from %d: %s\n", s, it->ToString().c_str());
849         }
850         dprintf(out, "Pull from %d: Received %zu elements\n", s, stats.size());
851         return NO_ERROR;
852     }
853     return UNKNOWN_ERROR;
854 }
855 
cmd_remove_all_configs(int out)856 status_t StatsService::cmd_remove_all_configs(int out) {
857     dprintf(out, "Removing all configs...\n");
858     VLOG("StatsService::cmd_remove_all_configs was called");
859     mConfigManager->RemoveAllConfigs();
860     StorageManager::deleteAllFiles(STATS_SERVICE_DIR);
861     return NO_ERROR;
862 }
863 
cmd_dump_memory_info(int out)864 status_t StatsService::cmd_dump_memory_info(int out) {
865     dprintf(out, "meminfo not available.\n");
866     return NO_ERROR;
867 }
868 
cmd_clear_puller_cache(int out)869 status_t StatsService::cmd_clear_puller_cache(int out) {
870     VLOG("StatsService::cmd_clear_puller_cache with Pid %i, Uid %i",
871             AIBinder_getCallingPid(), AIBinder_getCallingUid());
872     if (checkPermission(kPermissionDump)) {
873         int cleared = mPullerManager->ForceClearPullerCache();
874         dprintf(out, "Puller removed %d cached data!\n", cleared);
875         return NO_ERROR;
876     } else {
877         return PERMISSION_DENIED;
878     }
879 }
880 
cmd_print_logs(int out,const Vector<String8> & args)881 status_t StatsService::cmd_print_logs(int out, const Vector<String8>& args) {
882     Status status = checkUid(AID_ROOT);
883     if (!status.isOk()) {
884         return PERMISSION_DENIED;
885     }
886 
887     VLOG("StatsService::cmd_print_logs with pid %i, uid %i", AIBinder_getCallingPid(),
888          AIBinder_getCallingUid());
889     bool enabled = true;
890     if (args.size() >= 2) {
891         enabled = atoi(args[1].c_str()) != 0;
892     }
893     mProcessor->setPrintLogs(enabled);
894     return NO_ERROR;
895 }
896 
getUidFromArgs(const Vector<String8> & args,size_t uidArgIndex,int32_t & uid)897 bool StatsService::getUidFromArgs(const Vector<String8>& args, size_t uidArgIndex, int32_t& uid) {
898     return getUidFromString(args[uidArgIndex].c_str(), uid);
899 }
900 
getUidFromString(const char * s,int32_t & uid)901 bool StatsService::getUidFromString(const char* s, int32_t& uid) {
902     if (*s == '\0') {
903         return false;
904     }
905     char* endc = NULL;
906     int64_t longUid = strtol(s, &endc, 0);
907     if (*endc != '\0') {
908         return false;
909     }
910     int32_t goodUid = static_cast<int32_t>(longUid);
911     if (longUid < 0 || static_cast<uint64_t>(longUid) != static_cast<uid_t>(goodUid)) {
912         return false;  // It was not of uid_t type.
913     }
914     uid = goodUid;
915 
916     int32_t callingUid = AIBinder_getCallingUid();
917     return mEngBuild // UserDebug/EngBuild are allowed to impersonate uids.
918             || (callingUid == goodUid) // Anyone can 'impersonate' themselves.
919             || (callingUid == AID_ROOT && goodUid == AID_SHELL); // ROOT can impersonate SHELL.
920 }
921 
informAllUidData(const ScopedFileDescriptor & fd)922 Status StatsService::informAllUidData(const ScopedFileDescriptor& fd) {
923     ENFORCE_UID(AID_SYSTEM);
924     // Read stream into buffer.
925     string buffer;
926     if (!android::base::ReadFdToString(fd.get(), &buffer)) {
927         return exception(EX_ILLEGAL_ARGUMENT, "Failed to read all data from the pipe.");
928     }
929 
930     // Parse buffer.
931     UidData uidData;
932     if (!uidData.ParseFromString(buffer)) {
933         return exception(EX_ILLEGAL_ARGUMENT, "Error parsing proto stream for UidData.");
934     }
935 
936     vector<String16> versionStrings;
937     vector<String16> installers;
938     vector<String16> packageNames;
939     vector<int32_t> uids;
940     vector<int64_t> versions;
941     vector<vector<uint8_t>> certificateHashes;
942 
943     const auto numEntries = uidData.app_info_size();
944     versionStrings.reserve(numEntries);
945     installers.reserve(numEntries);
946     packageNames.reserve(numEntries);
947     uids.reserve(numEntries);
948     versions.reserve(numEntries);
949     certificateHashes.reserve(numEntries);
950 
951     for (const auto& appInfo: uidData.app_info()) {
952         packageNames.emplace_back(String16(appInfo.package_name().c_str()));
953         uids.push_back(appInfo.uid());
954         versions.push_back(appInfo.version());
955         versionStrings.emplace_back(String16(appInfo.version_string().c_str()));
956         installers.emplace_back(String16(appInfo.installer().c_str()));
957 
958         const string& certHash = appInfo.certificate_hash();
959         certificateHashes.emplace_back(certHash.begin(), certHash.end());
960     }
961 
962     mUidMap->updateMap(getElapsedRealtimeNs(), uids, versions, versionStrings, packageNames,
963                        installers, certificateHashes);
964 
965     mBootCompleteTrigger.markComplete(kUidMapReceivedTag);
966     VLOG("StatsService::informAllUidData UidData proto parsed successfully.");
967     return Status::ok();
968 }
969 
informOnePackage(const string & app,int32_t uid,int64_t version,const string & versionString,const string & installer,const vector<uint8_t> & certificateHash)970 Status StatsService::informOnePackage(const string& app, int32_t uid, int64_t version,
971                                       const string& versionString, const string& installer,
972                                       const vector<uint8_t>& certificateHash) {
973     ENFORCE_UID(AID_SYSTEM);
974 
975     VLOG("StatsService::informOnePackage was called");
976     String16 utf16App = String16(app.c_str());
977     String16 utf16VersionString = String16(versionString.c_str());
978     String16 utf16Installer = String16(installer.c_str());
979 
980     mUidMap->updateApp(getElapsedRealtimeNs(), utf16App, uid, version, utf16VersionString,
981                        utf16Installer, certificateHash);
982     return Status::ok();
983 }
984 
informOnePackageRemoved(const string & app,int32_t uid)985 Status StatsService::informOnePackageRemoved(const string& app, int32_t uid) {
986     ENFORCE_UID(AID_SYSTEM);
987 
988     VLOG("StatsService::informOnePackageRemoved was called");
989     String16 utf16App = String16(app.c_str());
990     mUidMap->removeApp(getElapsedRealtimeNs(), utf16App, uid);
991     mConfigManager->RemoveConfigs(uid);
992     return Status::ok();
993 }
994 
informAnomalyAlarmFired()995 Status StatsService::informAnomalyAlarmFired() {
996     ENFORCE_UID(AID_SYSTEM);
997     // Anomaly alarms are handled internally now. This code should be fully deleted.
998     return Status::ok();
999 }
1000 
informAlarmForSubscriberTriggeringFired()1001 Status StatsService::informAlarmForSubscriberTriggeringFired() {
1002     ENFORCE_UID(AID_SYSTEM);
1003 
1004     VLOG("StatsService::informAlarmForSubscriberTriggeringFired was called");
1005     int64_t currentTimeSec = getElapsedRealtimeSec();
1006     std::unordered_set<sp<const InternalAlarm>, SpHash<InternalAlarm>> alarmSet =
1007             mPeriodicAlarmMonitor->popSoonerThan(static_cast<uint32_t>(currentTimeSec));
1008     if (alarmSet.size() > 0) {
1009         VLOG("Found periodic alarm fired.");
1010         mProcessor->onPeriodicAlarmFired(currentTimeSec * NS_PER_SEC, alarmSet);
1011     } else {
1012         ALOGW("Cannot find an periodic alarm that fired. Perhaps it was recently cancelled.");
1013     }
1014     return Status::ok();
1015 }
1016 
informPollAlarmFired()1017 Status StatsService::informPollAlarmFired() {
1018     ENFORCE_UID(AID_SYSTEM);
1019 
1020     VLOG("StatsService::informPollAlarmFired was called");
1021     mProcessor->informPullAlarmFired(getElapsedRealtimeNs());
1022     VLOG("StatsService::informPollAlarmFired succeeded");
1023     return Status::ok();
1024 }
1025 
systemRunning()1026 Status StatsService::systemRunning() {
1027     ENFORCE_UID(AID_SYSTEM);
1028 
1029     // When system_server is up and running, schedule the dropbox task to run.
1030     VLOG("StatsService::systemRunning");
1031     sayHiToStatsCompanion();
1032     return Status::ok();
1033 }
1034 
informDeviceShutdown()1035 Status StatsService::informDeviceShutdown() {
1036     ENFORCE_UID(AID_SYSTEM);
1037     VLOG("StatsService::informDeviceShutdown");
1038     int64_t elapsedRealtimeNs = getElapsedRealtimeNs();
1039     int64_t wallClockNs = getWallClockNs();
1040     mProcessor->WriteDataToDisk(DEVICE_SHUTDOWN, FAST, elapsedRealtimeNs, wallClockNs);
1041     mProcessor->SaveActiveConfigsToDisk(elapsedRealtimeNs);
1042     mProcessor->SaveMetadataToDisk(wallClockNs, elapsedRealtimeNs);
1043     return Status::ok();
1044 }
1045 
sayHiToStatsCompanion()1046 void StatsService::sayHiToStatsCompanion() {
1047     shared_ptr<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1048     if (statsCompanion != nullptr) {
1049         VLOG("Telling statsCompanion that statsd is ready");
1050         statsCompanion->statsdReady();
1051     } else {
1052         VLOG("Could not access statsCompanion");
1053     }
1054 }
1055 
statsCompanionReady()1056 Status StatsService::statsCompanionReady() {
1057     ENFORCE_UID(AID_SYSTEM);
1058 
1059     VLOG("StatsService::statsCompanionReady was called");
1060     shared_ptr<IStatsCompanionService> statsCompanion = getStatsCompanionService();
1061     if (statsCompanion == nullptr) {
1062         return exception(EX_NULL_POINTER,
1063                          "StatsCompanion unavailable despite it contacting statsd.");
1064     }
1065     VLOG("StatsService::statsCompanionReady linking to statsCompanion.");
1066     AIBinder_linkToDeath(statsCompanion->asBinder().get(),
1067                          mStatsCompanionServiceDeathRecipient.get(), this);
1068     mPullerManager->SetStatsCompanionService(statsCompanion);
1069     mAnomalyAlarmMonitor->setStatsCompanionService(statsCompanion);
1070     mPeriodicAlarmMonitor->setStatsCompanionService(statsCompanion);
1071     return Status::ok();
1072 }
1073 
bootCompleted()1074 Status StatsService::bootCompleted() {
1075     ENFORCE_UID(AID_SYSTEM);
1076 
1077     VLOG("StatsService::bootCompleted was called");
1078     mBootCompleteTrigger.markComplete(kBootCompleteTag);
1079     return Status::ok();
1080 }
1081 
Startup()1082 void StatsService::Startup() {
1083     mConfigManager->Startup();
1084     mProcessor->LoadActiveConfigsFromDisk();
1085     mProcessor->LoadMetadataFromDisk(getWallClockNs(), getElapsedRealtimeNs());
1086 }
1087 
Terminate()1088 void StatsService::Terminate() {
1089     ALOGI("StatsService::Terminating");
1090     if (mProcessor != nullptr) {
1091         int64_t elapsedRealtimeNs = getElapsedRealtimeNs();
1092         int64_t wallClockNs = getWallClockNs();
1093         mProcessor->WriteDataToDisk(TERMINATION_SIGNAL_RECEIVED, FAST, elapsedRealtimeNs,
1094                                     wallClockNs);
1095         mProcessor->SaveActiveConfigsToDisk(elapsedRealtimeNs);
1096         mProcessor->SaveMetadataToDisk(wallClockNs, elapsedRealtimeNs);
1097     }
1098 }
1099 
1100 // Test only interface!!!
OnLogEvent(LogEvent * event)1101 void StatsService::OnLogEvent(LogEvent* event) {
1102     mProcessor->OnLogEvent(event);
1103     if (mShellSubscriber != nullptr) {
1104         mShellSubscriber->onLogEvent(*event);
1105     }
1106 }
1107 
getData(int64_t key,const int32_t callingUid,vector<uint8_t> * output)1108 Status StatsService::getData(int64_t key, const int32_t callingUid, vector<uint8_t>* output) {
1109     ENFORCE_UID(AID_SYSTEM);
1110 
1111     VLOG("StatsService::getData with Uid %i", callingUid);
1112     ConfigKey configKey(callingUid, key);
1113     // The dump latency does not matter here since we do not include the current bucket, we do not
1114     // need to pull any new data anyhow.
1115     mProcessor->onDumpReport(configKey, getElapsedRealtimeNs(), getWallClockNs(),
1116                              false /* include_current_bucket*/, true /* erase_data */,
1117                              GET_DATA_CALLED, FAST, output);
1118     return Status::ok();
1119 }
1120 
getMetadata(vector<uint8_t> * output)1121 Status StatsService::getMetadata(vector<uint8_t>* output) {
1122     ENFORCE_UID(AID_SYSTEM);
1123 
1124     StatsdStats::getInstance().dumpStats(output, false); // Don't reset the counters.
1125     return Status::ok();
1126 }
1127 
addConfiguration(int64_t key,const vector<uint8_t> & config,const int32_t callingUid)1128 Status StatsService::addConfiguration(int64_t key, const vector <uint8_t>& config,
1129                                       const int32_t callingUid) {
1130     ENFORCE_UID(AID_SYSTEM);
1131 
1132     if (addConfigurationChecked(callingUid, key, config)) {
1133         return Status::ok();
1134     } else {
1135         return exception(EX_ILLEGAL_ARGUMENT, "Could not parse malformatted StatsdConfig.");
1136     }
1137 }
1138 
addConfigurationChecked(int uid,int64_t key,const vector<uint8_t> & config)1139 bool StatsService::addConfigurationChecked(int uid, int64_t key, const vector<uint8_t>& config) {
1140     ConfigKey configKey(uid, key);
1141     StatsdConfig cfg;
1142     if (config.size() > 0) {  // If the config is empty, skip parsing.
1143         if (!cfg.ParseFromArray(&config[0], config.size())) {
1144             return false;
1145         }
1146     }
1147     mConfigManager->UpdateConfig(configKey, cfg);
1148     return true;
1149 }
1150 
removeDataFetchOperation(int64_t key,const int32_t callingUid)1151 Status StatsService::removeDataFetchOperation(int64_t key,
1152                                               const int32_t callingUid) {
1153     ENFORCE_UID(AID_SYSTEM);
1154     ConfigKey configKey(callingUid, key);
1155     mConfigManager->RemoveConfigReceiver(configKey);
1156     return Status::ok();
1157 }
1158 
setDataFetchOperation(int64_t key,const shared_ptr<IPendingIntentRef> & pir,const int32_t callingUid)1159 Status StatsService::setDataFetchOperation(int64_t key,
1160                                            const shared_ptr<IPendingIntentRef>& pir,
1161                                            const int32_t callingUid) {
1162     ENFORCE_UID(AID_SYSTEM);
1163 
1164     ConfigKey configKey(callingUid, key);
1165     mConfigManager->SetConfigReceiver(configKey, pir);
1166     if (StorageManager::hasConfigMetricsReport(configKey)) {
1167         VLOG("StatsService::setDataFetchOperation marking configKey %s to dump reports on disk",
1168              configKey.ToString().c_str());
1169         mProcessor->noteOnDiskData(configKey);
1170     }
1171     return Status::ok();
1172 }
1173 
setActiveConfigsChangedOperation(const shared_ptr<IPendingIntentRef> & pir,const int32_t callingUid,vector<int64_t> * output)1174 Status StatsService::setActiveConfigsChangedOperation(const shared_ptr<IPendingIntentRef>& pir,
1175                                                       const int32_t callingUid,
1176                                                       vector<int64_t>* output) {
1177     ENFORCE_UID(AID_SYSTEM);
1178 
1179     mConfigManager->SetActiveConfigsChangedReceiver(callingUid, pir);
1180     if (output != nullptr) {
1181         mProcessor->GetActiveConfigs(callingUid, *output);
1182     } else {
1183         ALOGW("StatsService::setActiveConfigsChanged output was nullptr");
1184     }
1185     return Status::ok();
1186 }
1187 
removeActiveConfigsChangedOperation(const int32_t callingUid)1188 Status StatsService::removeActiveConfigsChangedOperation(const int32_t callingUid) {
1189     ENFORCE_UID(AID_SYSTEM);
1190 
1191     mConfigManager->RemoveActiveConfigsChangedReceiver(callingUid);
1192     return Status::ok();
1193 }
1194 
removeConfiguration(int64_t key,const int32_t callingUid)1195 Status StatsService::removeConfiguration(int64_t key, const int32_t callingUid) {
1196     ENFORCE_UID(AID_SYSTEM);
1197 
1198     ConfigKey configKey(callingUid, key);
1199     mConfigManager->RemoveConfig(configKey);
1200     return Status::ok();
1201 }
1202 
setBroadcastSubscriber(int64_t configId,int64_t subscriberId,const shared_ptr<IPendingIntentRef> & pir,const int32_t callingUid)1203 Status StatsService::setBroadcastSubscriber(int64_t configId,
1204                                             int64_t subscriberId,
1205                                             const shared_ptr<IPendingIntentRef>& pir,
1206                                             const int32_t callingUid) {
1207     ENFORCE_UID(AID_SYSTEM);
1208 
1209     VLOG("StatsService::setBroadcastSubscriber called.");
1210     ConfigKey configKey(callingUid, configId);
1211     SubscriberReporter::getInstance()
1212             .setBroadcastSubscriber(configKey, subscriberId, pir);
1213     return Status::ok();
1214 }
1215 
unsetBroadcastSubscriber(int64_t configId,int64_t subscriberId,const int32_t callingUid)1216 Status StatsService::unsetBroadcastSubscriber(int64_t configId,
1217                                               int64_t subscriberId,
1218                                               const int32_t callingUid) {
1219     ENFORCE_UID(AID_SYSTEM);
1220 
1221     VLOG("StatsService::unsetBroadcastSubscriber called.");
1222     ConfigKey configKey(callingUid, configId);
1223     SubscriberReporter::getInstance()
1224             .unsetBroadcastSubscriber(configKey, subscriberId);
1225     return Status::ok();
1226 }
1227 
allPullersFromBootRegistered()1228 Status StatsService::allPullersFromBootRegistered() {
1229     ENFORCE_UID(AID_SYSTEM);
1230 
1231     VLOG("StatsService::allPullersFromBootRegistered was called");
1232     mBootCompleteTrigger.markComplete(kAllPullersRegisteredTag);
1233     return Status::ok();
1234 }
1235 
registerPullAtomCallback(int32_t uid,int32_t atomTag,int64_t coolDownMillis,int64_t timeoutMillis,const std::vector<int32_t> & additiveFields,const shared_ptr<IPullAtomCallback> & pullerCallback)1236 Status StatsService::registerPullAtomCallback(int32_t uid, int32_t atomTag, int64_t coolDownMillis,
1237                                               int64_t timeoutMillis,
1238                                               const std::vector<int32_t>& additiveFields,
1239                                               const shared_ptr<IPullAtomCallback>& pullerCallback) {
1240     ENFORCE_UID(AID_SYSTEM);
1241     VLOG("StatsService::registerPullAtomCallback called.");
1242     mPullerManager->RegisterPullAtomCallback(uid, atomTag, MillisToNano(coolDownMillis),
1243                                              MillisToNano(timeoutMillis), additiveFields,
1244                                              pullerCallback);
1245     return Status::ok();
1246 }
1247 
registerNativePullAtomCallback(int32_t atomTag,int64_t coolDownMillis,int64_t timeoutMillis,const std::vector<int32_t> & additiveFields,const shared_ptr<IPullAtomCallback> & pullerCallback)1248 Status StatsService::registerNativePullAtomCallback(
1249         int32_t atomTag, int64_t coolDownMillis, int64_t timeoutMillis,
1250         const std::vector<int32_t>& additiveFields,
1251         const shared_ptr<IPullAtomCallback>& pullerCallback) {
1252     if (!checkPermission(kPermissionRegisterPullAtom)) {
1253         return exception(
1254                 EX_SECURITY,
1255                 StringPrintf("Uid %d does not have the %s permission when registering atom %d",
1256                              AIBinder_getCallingUid(), kPermissionRegisterPullAtom, atomTag));
1257     }
1258     VLOG("StatsService::registerNativePullAtomCallback called.");
1259     int32_t uid = AIBinder_getCallingUid();
1260     mPullerManager->RegisterPullAtomCallback(uid, atomTag, MillisToNano(coolDownMillis),
1261                                              MillisToNano(timeoutMillis), additiveFields,
1262                                              pullerCallback);
1263     return Status::ok();
1264 }
1265 
unregisterPullAtomCallback(int32_t uid,int32_t atomTag)1266 Status StatsService::unregisterPullAtomCallback(int32_t uid, int32_t atomTag) {
1267     ENFORCE_UID(AID_SYSTEM);
1268     VLOG("StatsService::unregisterPullAtomCallback called.");
1269     mPullerManager->UnregisterPullAtomCallback(uid, atomTag);
1270     return Status::ok();
1271 }
1272 
unregisterNativePullAtomCallback(int32_t atomTag)1273 Status StatsService::unregisterNativePullAtomCallback(int32_t atomTag) {
1274     if (!checkPermission(kPermissionRegisterPullAtom)) {
1275         return exception(
1276                 EX_SECURITY,
1277                 StringPrintf("Uid %d does not have the %s permission when unregistering atom %d",
1278                              AIBinder_getCallingUid(), kPermissionRegisterPullAtom, atomTag));
1279     }
1280     VLOG("StatsService::unregisterNativePullAtomCallback called.");
1281     int32_t uid = AIBinder_getCallingUid();
1282     mPullerManager->UnregisterPullAtomCallback(uid, atomTag);
1283     return Status::ok();
1284 }
1285 
getRegisteredExperimentIds(std::vector<int64_t> * experimentIdsOut)1286 Status StatsService::getRegisteredExperimentIds(std::vector<int64_t>* experimentIdsOut) {
1287     ENFORCE_UID(AID_SYSTEM);
1288     // TODO: add verifier permission
1289 
1290     experimentIdsOut->clear();
1291     // Read the latest train info
1292     vector<InstallTrainInfo> trainInfoList = StorageManager::readAllTrainInfo();
1293     if (trainInfoList.empty()) {
1294         // No train info means no experiment IDs, return an empty list
1295         return Status::ok();
1296     }
1297 
1298     // Copy the experiment IDs to the out vector
1299     for (InstallTrainInfo& trainInfo : trainInfoList) {
1300         experimentIdsOut->insert(experimentIdsOut->end(),
1301                                  trainInfo.experimentIds.begin(),
1302                                  trainInfo.experimentIds.end());
1303     }
1304     return Status::ok();
1305 }
1306 
updateProperties(const vector<PropertyParcel> & properties)1307 Status StatsService::updateProperties(const vector<PropertyParcel>& properties) {
1308     ENFORCE_UID(AID_SYSTEM);
1309 
1310     for (const auto& [property, value] : properties) {
1311         if (property == kIncludeCertificateHash) {
1312             mUidMap->setIncludeCertificateHash(value == "true");
1313         }
1314     }
1315     return Status::ok();
1316 }
1317 
statsCompanionServiceDied(void * cookie)1318 void StatsService::statsCompanionServiceDied(void* cookie) {
1319     auto thiz = static_cast<StatsService*>(cookie);
1320     thiz->statsCompanionServiceDiedImpl();
1321 }
1322 
statsCompanionServiceDiedImpl()1323 void StatsService::statsCompanionServiceDiedImpl() {
1324     ALOGW("statscompanion service died");
1325     StatsdStats::getInstance().noteSystemServerRestart(getWallClockSec());
1326     if (mProcessor != nullptr) {
1327         ALOGW("Reset statsd upon system server restarts.");
1328         int64_t systemServerRestartNs = getElapsedRealtimeNs();
1329         int64_t wallClockNs = getWallClockNs();
1330         ProtoOutputStream activeConfigsProto;
1331         mProcessor->WriteActiveConfigsToProtoOutputStream(systemServerRestartNs,
1332                 STATSCOMPANION_DIED, &activeConfigsProto);
1333         metadata::StatsMetadataList metadataList;
1334         mProcessor->WriteMetadataToProto(wallClockNs, systemServerRestartNs, &metadataList);
1335         mProcessor->WriteDataToDisk(STATSCOMPANION_DIED, FAST, systemServerRestartNs, wallClockNs);
1336         mProcessor->resetConfigs();
1337 
1338         std::string serializedActiveConfigs;
1339         if (activeConfigsProto.serializeToString(&serializedActiveConfigs)) {
1340             ActiveConfigList activeConfigs;
1341             if (activeConfigs.ParseFromString(serializedActiveConfigs)) {
1342                 mProcessor->SetConfigsActiveState(activeConfigs, systemServerRestartNs);
1343             }
1344         }
1345         mProcessor->SetMetadataState(metadataList, wallClockNs, systemServerRestartNs);
1346     }
1347     mAnomalyAlarmMonitor->setStatsCompanionService(nullptr);
1348     mPeriodicAlarmMonitor->setStatsCompanionService(nullptr);
1349     mPullerManager->SetStatsCompanionService(nullptr);
1350 }
1351 
1352 }  // namespace statsd
1353 }  // namespace os
1354 }  // namespace android
1355