1 /*
2  * Copyright (C) 2020 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 // TODO(b/298459533): metrics_reporter_in_the_daemon ramp up -> remove old
18 // code
19 
20 #include <signal.h>
21 #include <cstdlib>
22 #include <fstream>
23 
24 #include "chre_host/config_util.h"
25 #include "chre_host/daemon_base.h"
26 #include "chre_host/file_stream.h"
27 #include "chre_host/log.h"
28 #include "chre_host/napp_header.h"
29 
30 #ifdef CHRE_DAEMON_METRIC_ENABLED
31 #include <android_chre_flags.h>
32 #include <chre_atoms_log.h>
33 #include <system/chre/core/chre_metrics.pb.h>
34 #endif  // CHRE_DAEMON_METRIC_ENABLED
35 
36 // Aliased for consistency with the way these symbols are referenced in
37 // CHRE-side code
38 namespace fbs = ::chre::fbs;
39 
40 namespace android {
41 namespace chre {
42 
43 #ifdef CHRE_DAEMON_METRIC_ENABLED
44 using ::aidl::android::frameworks::stats::IStats;
45 using ::aidl::android::frameworks::stats::VendorAtom;
46 using ::aidl::android::frameworks::stats::VendorAtomValue;
47 
48 using ::android::chre::Atoms::CHRE_EVENT_QUEUE_SNAPSHOT_REPORTED;
49 using ::android::chre::Atoms::CHRE_PAL_OPEN_FAILED;
50 using ::android::chre::Atoms::ChrePalOpenFailed;
51 using ::android::chre::flags::metrics_reporter_in_the_daemon;
52 #endif  // CHRE_DAEMON_METRIC_ENABLED
53 
54 namespace {
55 
signalHandler(void * ctx)56 void signalHandler(void *ctx) {
57   auto *daemon = static_cast<ChreDaemonBase *>(ctx);
58   int rc = -1;
59   sigset_t signalMask;
60   sigfillset(&signalMask);
61   sigdelset(&signalMask, SIGINT);
62   sigdelset(&signalMask, SIGTERM);
63   if (sigprocmask(SIG_SETMASK, &signalMask, NULL) != 0) {
64     LOG_ERROR("Couldn't mask all signals except INT/TERM", errno);
65   }
66 
67   while (true) {
68     int signum = 0;
69     if ((rc = sigwait(&signalMask, &signum)) != 0) {
70       LOGE("Sigwait failed: %d", rc);
71     }
72     LOGI("Received signal %d", signum);
73     if (signum == SIGINT || signum == SIGTERM) {
74       daemon->onShutdown();
75       break;
76     }
77   }
78 }
79 
80 }  // anonymous namespace
81 
ChreDaemonBase()82 ChreDaemonBase::ChreDaemonBase() : mChreShutdownRequested(false) {
83   mLogger.init();
84   // TODO(b/297388964): Replace thread with handler installed via std::signal()
85   mSignalHandlerThread = std::thread(signalHandler, this);
86 }
87 
loadPreloadedNanoapps()88 void ChreDaemonBase::loadPreloadedNanoapps() {
89   const std::string kPreloadedNanoappsConfigPath =
90       "/vendor/etc/chre/preloaded_nanoapps.json";
91   std::string directory;
92   std::vector<std::string> nanoapps;
93   bool success = getPreloadedNanoappsFromConfigFile(
94       kPreloadedNanoappsConfigPath, directory, nanoapps);
95   if (!success) {
96     LOGE("Failed to parse preloaded nanoapps config file");
97     return;
98   }
99 
100   for (uint32_t i = 0; i < nanoapps.size(); ++i) {
101     loadPreloadedNanoapp(directory, nanoapps[i], i);
102   }
103 }
104 
loadPreloadedNanoapp(const std::string & directory,const std::string & name,uint32_t transactionId)105 void ChreDaemonBase::loadPreloadedNanoapp(const std::string &directory,
106                                           const std::string &name,
107                                           uint32_t transactionId) {
108   std::vector<uint8_t> headerBuffer;
109 
110   std::string headerFile = directory + "/" + name + ".napp_header";
111 
112   // Only create the nanoapp filename as the CHRE framework will load from
113   // within the directory its own binary resides in.
114   std::string nanoappFilename = name + ".so";
115 
116   if (!readFileContents(headerFile.c_str(), headerBuffer) ||
117       !loadNanoapp(headerBuffer, nanoappFilename, transactionId)) {
118     LOGE("Failed to load nanoapp: '%s'", name.c_str());
119   }
120 }
121 
loadNanoapp(const std::vector<uint8_t> & header,const std::string & nanoappName,uint32_t transactionId)122 bool ChreDaemonBase::loadNanoapp(const std::vector<uint8_t> &header,
123                                  const std::string &nanoappName,
124                                  uint32_t transactionId) {
125   bool success = false;
126   if (header.size() != sizeof(NanoAppBinaryHeader)) {
127     LOGE("Header size mismatch");
128   } else {
129     // The header blob contains the struct above.
130     const auto *appHeader =
131         reinterpret_cast<const NanoAppBinaryHeader *>(header.data());
132 
133     // Build the target API version from major and minor.
134     uint32_t targetApiVersion = (appHeader->targetChreApiMajorVersion << 24) |
135                                 (appHeader->targetChreApiMinorVersion << 16);
136 
137     success = sendNanoappLoad(appHeader->appId, appHeader->appVersion,
138                               targetApiVersion, nanoappName, transactionId);
139   }
140 
141   return success;
142 }
143 
sendTimeSyncWithRetry(size_t numRetries,useconds_t retryDelayUs,bool logOnError)144 bool ChreDaemonBase::sendTimeSyncWithRetry(size_t numRetries,
145                                            useconds_t retryDelayUs,
146                                            bool logOnError) {
147   bool success = false;
148   while (!success && (numRetries-- != 0)) {
149     success = sendTimeSync(logOnError);
150     if (!success) {
151       usleep(retryDelayUs);
152     }
153   }
154   return success;
155 }
156 
handleNanConfigurationRequest(const::chre::fbs::NanConfigurationRequestT *)157 void ChreDaemonBase::handleNanConfigurationRequest(
158     const ::chre::fbs::NanConfigurationRequestT * /*request*/) {
159   LOGE("NAN is unsupported on this platform");
160 }
161 
162 #ifdef CHRE_DAEMON_METRIC_ENABLED
handleMetricLog(const::chre::fbs::MetricLogT * metricMsg)163 void ChreDaemonBase::handleMetricLog(const ::chre::fbs::MetricLogT *metricMsg) {
164   const std::vector<int8_t> &encodedMetric = metricMsg->encoded_metric;
165 
166   switch (metricMsg->id) {
167     case CHRE_PAL_OPEN_FAILED: {
168       metrics::ChrePalOpenFailed metric;
169       if (!metric.ParseFromArray(encodedMetric.data(), encodedMetric.size())) {
170         LOGE("Failed to parse metric data");
171       } else {
172         if (metrics_reporter_in_the_daemon()) {
173           ChrePalOpenFailed::ChrePalType pal =
174               static_cast<ChrePalOpenFailed::ChrePalType>(metric.pal());
175           ChrePalOpenFailed::Type type =
176               static_cast<ChrePalOpenFailed::Type>(metric.type());
177           if (!mMetricsReporter.logPalOpenFailed(pal, type)) {
178             LOGE("Could not log the PAL open failed metric");
179           }
180         } else {
181           std::vector<VendorAtomValue> values(2);
182           values[0].set<VendorAtomValue::intValue>(metric.pal());
183           values[1].set<VendorAtomValue::intValue>(metric.type());
184           const VendorAtom atom{
185               .atomId = Atoms::CHRE_PAL_OPEN_FAILED,
186               .values{std::move(values)},
187           };
188           reportMetric(atom);
189         }
190       }
191       break;
192     }
193     case CHRE_EVENT_QUEUE_SNAPSHOT_REPORTED: {
194       metrics::ChreEventQueueSnapshotReported metric;
195       if (!metric.ParseFromArray(encodedMetric.data(), encodedMetric.size())) {
196         LOGE("Failed to parse metric data");
197       } else {
198         if (metrics_reporter_in_the_daemon()) {
199           if (!mMetricsReporter.logEventQueueSnapshotReported(
200                   metric.snapshot_chre_get_time_ms(),
201                   metric.max_event_queue_size(), metric.mean_event_queue_size(),
202                   metric.num_dropped_events())) {
203             LOGE("Could not log the event queue snapshot metric");
204           }
205         } else {
206           std::vector<VendorAtomValue> values(6);
207           values[0].set<VendorAtomValue::intValue>(
208               metric.snapshot_chre_get_time_ms());
209           values[1].set<VendorAtomValue::intValue>(
210               metric.max_event_queue_size());
211           values[2].set<VendorAtomValue::intValue>(
212               metric.mean_event_queue_size());
213           values[3].set<VendorAtomValue::intValue>(metric.num_dropped_events());
214           // Last two values are not currently populated and will be implemented
215           // later. To avoid confusion of the interpretation, we use UINT32_MAX
216           // as a placeholder value.
217           values[4].set<VendorAtomValue::intValue>(
218               UINT32_MAX);  // max_queue_delay_us
219           values[5].set<VendorAtomValue::intValue>(
220               UINT32_MAX);  // mean_queue_delay_us
221           const VendorAtom atom{
222               .atomId = Atoms::CHRE_EVENT_QUEUE_SNAPSHOT_REPORTED,
223               .values{std::move(values)},
224           };
225           reportMetric(atom);
226         }
227       }
228       break;
229     }
230     default: {
231 #ifdef CHRE_LOG_ATOM_EXTENSION_ENABLED
232       handleVendorMetricLog(metricMsg);
233 #else
234       LOGW("Unknown metric ID %" PRIu32, metricMsg->id);
235 #endif  // CHRE_LOG_ATOM_EXTENSION_ENABLED
236     }
237   }
238 }
239 
reportMetric(const VendorAtom & atom)240 void ChreDaemonBase::reportMetric(const VendorAtom &atom) {
241   const std::string statsServiceName =
242       std::string(IStats::descriptor).append("/default");
243   if (!AServiceManager_isDeclared(statsServiceName.c_str())) {
244     LOGE("Stats service is not declared.");
245     return;
246   }
247 
248   std::shared_ptr<IStats> stats_client = IStats::fromBinder(ndk::SpAIBinder(
249       AServiceManager_waitForService(statsServiceName.c_str())));
250   if (stats_client == nullptr) {
251     LOGE("Failed to get IStats service");
252     return;
253   }
254 
255   const ndk::ScopedAStatus ret = stats_client->reportVendorAtom(atom);
256   if (!ret.isOk()) {
257     LOGE("Failed to report vendor atom");
258   }
259 }
260 #endif  // CHRE_DAEMON_METRIC_ENABLED
261 
262 }  // namespace chre
263 }  // namespace android
264