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 #define LOG_TAG "carwatchdogd"
18 
19 #include "IoOveruseConfigs.h"
20 
21 #include "OveruseConfigurationXmlHelper.h"
22 #include "PackageInfoResolver.h"
23 
24 #include <android-base/strings.h>
25 #include <log/log.h>
26 
27 #include <inttypes.h>
28 
29 #include <filesystem>
30 #include <limits>
31 
32 namespace android {
33 namespace automotive {
34 namespace watchdog {
35 
36 using ::aidl::android::automotive::watchdog::PerStateBytes;
37 using ::aidl::android::automotive::watchdog::internal::ApplicationCategoryType;
38 using ::aidl::android::automotive::watchdog::internal::ComponentType;
39 using ::aidl::android::automotive::watchdog::internal::IoOveruseAlertThreshold;
40 using ::aidl::android::automotive::watchdog::internal::IoOveruseConfiguration;
41 using ::aidl::android::automotive::watchdog::internal::PackageInfo;
42 using ::aidl::android::automotive::watchdog::internal::PackageMetadata;
43 using ::aidl::android::automotive::watchdog::internal::PerStateIoOveruseThreshold;
44 using ::aidl::android::automotive::watchdog::internal::ResourceOveruseConfiguration;
45 using ::aidl::android::automotive::watchdog::internal::ResourceSpecificConfiguration;
46 using ::aidl::android::automotive::watchdog::internal::UidType;
47 using ::android::base::Error;
48 using ::android::base::Result;
49 using ::android::base::StartsWith;
50 using ::android::base::StringAppendF;
51 using ::android::base::StringPrintf;
52 
53 namespace {
54 
55 // Enum to filter the updatable overuse configs by each component.
56 enum OveruseConfigEnum {
57     COMPONENT_SPECIFIC_SAFE_TO_KILL_PACKAGES = 1 << 0,
58     VENDOR_PACKAGE_PREFIXES = 1 << 1,
59     PACKAGE_APP_CATEGORY_MAPPINGS = 1 << 2,
60     COMPONENT_SPECIFIC_GENERIC_THRESHOLDS = 1 << 3,
61     COMPONENT_SPECIFIC_PER_PACKAGE_THRESHOLDS = 1 << 4,
62     PER_CATEGORY_THRESHOLDS = 1 << 5,
63     SYSTEM_WIDE_ALERT_THRESHOLDS = 1 << 6,
64 };
65 
66 const int32_t kSystemComponentUpdatableConfigs = COMPONENT_SPECIFIC_SAFE_TO_KILL_PACKAGES |
67         PACKAGE_APP_CATEGORY_MAPPINGS | COMPONENT_SPECIFIC_GENERIC_THRESHOLDS |
68         COMPONENT_SPECIFIC_PER_PACKAGE_THRESHOLDS | SYSTEM_WIDE_ALERT_THRESHOLDS;
69 const int32_t kVendorComponentUpdatableConfigs = COMPONENT_SPECIFIC_SAFE_TO_KILL_PACKAGES |
70         VENDOR_PACKAGE_PREFIXES | PACKAGE_APP_CATEGORY_MAPPINGS |
71         COMPONENT_SPECIFIC_GENERIC_THRESHOLDS | COMPONENT_SPECIFIC_PER_PACKAGE_THRESHOLDS |
72         PER_CATEGORY_THRESHOLDS;
73 const int32_t kThirdPartyComponentUpdatableConfigs = COMPONENT_SPECIFIC_GENERIC_THRESHOLDS;
74 
toStringVector(const std::unordered_set<std::string> & values)75 const std::vector<std::string> toStringVector(const std::unordered_set<std::string>& values) {
76     std::vector<std::string> output;
77     for (const auto& v : values) {
78         if (!v.empty()) {
79             output.emplace_back(v);
80         }
81     }
82     return output;
83 }
84 
toString(const PerStateIoOveruseThreshold & thresholds)85 std::string toString(const PerStateIoOveruseThreshold& thresholds) {
86     return StringPrintf("name=%s, foregroundBytes=%" PRId64 ", backgroundBytes=%" PRId64
87                         ", garageModeBytes=%" PRId64,
88                         thresholds.name.c_str(), thresholds.perStateWriteBytes.foregroundBytes,
89                         thresholds.perStateWriteBytes.backgroundBytes,
90                         thresholds.perStateWriteBytes.garageModeBytes);
91 }
92 
containsValidThresholds(const PerStateIoOveruseThreshold & thresholds)93 Result<void> containsValidThresholds(const PerStateIoOveruseThreshold& thresholds) {
94     if (thresholds.name.empty()) {
95         return Error() << "Doesn't contain threshold name";
96     }
97 
98     if (thresholds.perStateWriteBytes.foregroundBytes <= 0 ||
99         thresholds.perStateWriteBytes.backgroundBytes <= 0 ||
100         thresholds.perStateWriteBytes.garageModeBytes <= 0) {
101         return Error() << "Some thresholds are less than or equal to zero: "
102                        << toString(thresholds);
103     }
104     return {};
105 }
106 
containsValidThreshold(const IoOveruseAlertThreshold & threshold)107 Result<void> containsValidThreshold(const IoOveruseAlertThreshold& threshold) {
108     if (threshold.durationInSeconds <= 0) {
109         return Error() << "Duration must be greater than zero";
110     }
111     if (threshold.writtenBytesPerSecond <= 0) {
112         return Error() << "Written bytes/second must be greater than zero";
113     }
114     return {};
115 }
116 
toApplicationCategoryType(const std::string & value)117 ApplicationCategoryType toApplicationCategoryType(const std::string& value) {
118     if (value == "MAPS") {
119         return ApplicationCategoryType::MAPS;
120     }
121     if (value == "MEDIA") {
122         return ApplicationCategoryType::MEDIA;
123     }
124     return ApplicationCategoryType::OTHERS;
125 }
126 
isValidIoOveruseConfiguration(const ComponentType componentType,const int32_t updatableConfigsFilter,const IoOveruseConfiguration & ioOveruseConfig)127 Result<void> isValidIoOveruseConfiguration(const ComponentType componentType,
128                                            const int32_t updatableConfigsFilter,
129                                            const IoOveruseConfiguration& ioOveruseConfig) {
130     auto componentTypeStr = toString(componentType);
131     if (updatableConfigsFilter & OveruseConfigEnum::COMPONENT_SPECIFIC_GENERIC_THRESHOLDS) {
132         if (auto result = containsValidThresholds(ioOveruseConfig.componentLevelThresholds);
133             !result.ok()) {
134             return Error() << "Invalid " << toString(componentType)
135                            << " component level generic thresholds: " << result.error();
136         }
137         if (ioOveruseConfig.componentLevelThresholds.name != componentTypeStr) {
138             return Error() << "Invalid component name "
139                            << ioOveruseConfig.componentLevelThresholds.name
140                            << " in component level generic thresholds for component "
141                            << componentTypeStr;
142         }
143     }
144     const auto containsValidSystemWideThresholds = [&]() -> bool {
145         if (ioOveruseConfig.systemWideThresholds.empty()) {
146             return false;
147         }
148         for (const auto& threshold : ioOveruseConfig.systemWideThresholds) {
149             if (auto result = containsValidThreshold(threshold); !result.ok()) {
150                 return false;
151             }
152         }
153         return true;
154     };
155     if ((updatableConfigsFilter & OveruseConfigEnum::SYSTEM_WIDE_ALERT_THRESHOLDS) &&
156         !containsValidSystemWideThresholds()) {
157         return Error() << "Invalid system-wide alert threshold provided in " << componentTypeStr
158                        << " config";
159     }
160     return {};
161 }
162 
getComponentFilter(const ComponentType componentType)163 Result<int32_t> getComponentFilter(const ComponentType componentType) {
164     switch (componentType) {
165         case ComponentType::SYSTEM:
166             return kSystemComponentUpdatableConfigs;
167         case ComponentType::VENDOR:
168             return kVendorComponentUpdatableConfigs;
169         case ComponentType::THIRD_PARTY:
170             return kThirdPartyComponentUpdatableConfigs;
171         default:
172             return Error() << "Invalid component type: " << static_cast<int32_t>(componentType);
173     }
174 }
175 
isValidResourceOveruseConfig(const ResourceOveruseConfiguration & resourceOveruseConfig)176 Result<void> isValidResourceOveruseConfig(
177         const ResourceOveruseConfiguration& resourceOveruseConfig) {
178     const auto filter = getComponentFilter(resourceOveruseConfig.componentType);
179     if (!filter.ok()) {
180         return Error() << filter.error();
181     }
182     std::unordered_map<std::string, ApplicationCategoryType> seenCategoryMappings;
183     for (const auto& meta : resourceOveruseConfig.packageMetadata) {
184         if (const auto it = seenCategoryMappings.find(meta.packageName);
185             it != seenCategoryMappings.end() && it->second != meta.appCategoryType) {
186             return Error()
187                     << "Must provide exactly one application category mapping for the package "
188                     << meta.packageName << ": Provided mappings " << toString(meta.appCategoryType)
189                     << " and " << toString(it->second);
190         }
191         seenCategoryMappings[meta.packageName] = meta.appCategoryType;
192     }
193     if (resourceOveruseConfig.resourceSpecificConfigurations.size() != 1) {
194         return Error() << "Must provide exactly one I/O overuse configuration. Received "
195                        << resourceOveruseConfig.resourceSpecificConfigurations.size()
196                        << " configurations";
197     }
198     for (const auto& config : resourceOveruseConfig.resourceSpecificConfigurations) {
199         if (config.getTag() != ResourceSpecificConfiguration::ioOveruseConfiguration) {
200             return Error() << "Invalid resource type: " << static_cast<int32_t>(config.getTag());
201         }
202         const auto& ioOveruseConfig =
203                 config.get<ResourceSpecificConfiguration::ioOveruseConfiguration>();
204         if (auto result = isValidIoOveruseConfiguration(resourceOveruseConfig.componentType,
205                                                         *filter, ioOveruseConfig);
206             !result.ok()) {
207             return Error() << "Invalid I/O overuse configuration for component "
208                            << toString(resourceOveruseConfig.componentType).c_str() << ": "
209                            << result.error();
210         }
211     }
212     return {};
213 }
214 
isValidResourceOveruseConfigs(const std::vector<ResourceOveruseConfiguration> & resourceOveruseConfigs)215 Result<void> isValidResourceOveruseConfigs(
216         const std::vector<ResourceOveruseConfiguration>& resourceOveruseConfigs) {
217     std::unordered_set<ComponentType> seenComponentTypes;
218     for (const auto& resourceOveruseConfig : resourceOveruseConfigs) {
219         if (seenComponentTypes.count(resourceOveruseConfig.componentType) > 0) {
220             return Error() << "Cannot provide duplicate configs for the same component type "
221                            << toString(resourceOveruseConfig.componentType);
222         }
223         if (const auto result = isValidResourceOveruseConfig(resourceOveruseConfig); !result.ok()) {
224             return result;
225         }
226         seenComponentTypes.insert(resourceOveruseConfig.componentType);
227     }
228     return {};
229 }
230 
isSafeToKillAnyPackage(const std::vector<std::string> & packages,const std::unordered_set<std::string> & safeToKillPackages)231 bool isSafeToKillAnyPackage(const std::vector<std::string>& packages,
232                             const std::unordered_set<std::string>& safeToKillPackages) {
233     for (const auto& packageName : packages) {
234         if (safeToKillPackages.find(packageName) != safeToKillPackages.end()) {
235             return true;
236         }
237     }
238     return false;
239 }
240 
241 }  // namespace
242 
243 IoOveruseConfigs::ParseXmlFileFunction IoOveruseConfigs::sParseXmlFile =
244         &OveruseConfigurationXmlHelper::parseXmlFile;
245 IoOveruseConfigs::WriteXmlFileFunction IoOveruseConfigs::sWriteXmlFile =
246         &OveruseConfigurationXmlHelper::writeXmlFile;
247 
updatePerPackageThresholds(const std::vector<PerStateIoOveruseThreshold> & thresholds,const std::function<void (const std::string &)> & maybeAppendVendorPackagePrefixes)248 Result<void> ComponentSpecificConfig::updatePerPackageThresholds(
249         const std::vector<PerStateIoOveruseThreshold>& thresholds,
250         const std::function<void(const std::string&)>& maybeAppendVendorPackagePrefixes) {
251     mPerPackageThresholds.clear();
252     if (thresholds.empty()) {
253         return Error() << "\tNo per-package thresholds provided so clearing it\n";
254     }
255     std::string errorMsgs;
256     for (const auto& packageThreshold : thresholds) {
257         if (packageThreshold.name.empty()) {
258             StringAppendF(&errorMsgs, "\tSkipping per-package threshold without package name\n");
259             continue;
260         }
261         maybeAppendVendorPackagePrefixes(packageThreshold.name);
262         if (auto result = containsValidThresholds(packageThreshold); !result.ok()) {
263             StringAppendF(&errorMsgs,
264                           "\tSkipping invalid package specific thresholds for package '%s': %s\n",
265                           packageThreshold.name.c_str(), result.error().message().c_str());
266             continue;
267         }
268         if (const auto& it = mPerPackageThresholds.find(packageThreshold.name);
269             it != mPerPackageThresholds.end()) {
270             StringAppendF(&errorMsgs, "\tDuplicate threshold received for package '%s'\n",
271                           packageThreshold.name.c_str());
272         }
273         mPerPackageThresholds[packageThreshold.name] = packageThreshold;
274     }
275     return errorMsgs.empty() ? Result<void>{} : Error() << errorMsgs;
276 }
277 
updateSafeToKillPackages(const std::vector<std::string> & packages,const std::function<void (const std::string &)> & maybeAppendVendorPackagePrefixes)278 Result<void> ComponentSpecificConfig::updateSafeToKillPackages(
279         const std::vector<std::string>& packages,
280         const std::function<void(const std::string&)>& maybeAppendVendorPackagePrefixes) {
281     mSafeToKillPackages.clear();
282     if (packages.empty()) {
283         return Error() << "\tNo safe-to-kill packages provided so clearing it\n";
284     }
285     std::string errorMsgs;
286     for (const auto& packageName : packages) {
287         if (packageName.empty()) {
288             StringAppendF(&errorMsgs, "\tSkipping empty safe-to-kill package name");
289             continue;
290         }
291         maybeAppendVendorPackagePrefixes(packageName);
292         mSafeToKillPackages.insert(packageName);
293     }
294     return errorMsgs.empty() ? Result<void>{} : Error() << errorMsgs;
295 }
296 
IoOveruseConfigs()297 IoOveruseConfigs::IoOveruseConfigs() :
298       mSystemConfig({}),
299       mVendorConfig({}),
300       mThirdPartyConfig({}),
301       mPackagesToAppCategories({}),
302       mPackagesToAppCategoryMappingUpdateMode(OVERWRITE),
303       mPerCategoryThresholds({}),
304       mVendorPackagePrefixes({}) {
__anon5176544f0302(const char* filename, const char* configType) 305     const auto updateFromXmlPerType = [&](const char* filename, const char* configType) -> bool {
306         if (const auto result = this->updateFromXml(filename); !result.ok()) {
307             ALOGE("Failed to parse %s resource overuse configuration from '%s': %s", configType,
308                   filename, result.error().message().c_str());
309             return false;
310         }
311         ALOGI("Updated with %s resource overuse configuration from '%s'", configType, filename);
312         return true;
313     };
314     /*
315      * Package to app category mapping is common between system and vendor component configs. When
316      * the build system and vendor component configs are used, the mapping shouldn't be
317      * overwritten by either of the configs because the build configurations defined by the
318      * vendor or system components may not be aware of mappings included in other component's
319      * config. Ergo, the mapping from both the component configs should be merged together. When a
320      * latest config is used for either of the components, the latest mapping should be given higher
321      * priority.
322      */
323     bool isBuildSystemConfig = false;
324     if (!updateFromXmlPerType(kLatestSystemConfigXmlPath, "latest system")) {
325         isBuildSystemConfig = updateFromXmlPerType(kBuildSystemConfigXmlPath, "build system");
326     }
327     if (!updateFromXmlPerType(kLatestVendorConfigXmlPath, "latest vendor")) {
328         mPackagesToAppCategoryMappingUpdateMode = isBuildSystemConfig ? MERGE : NO_UPDATE;
329         if (!updateFromXmlPerType(kBuildVendorConfigXmlPath, "build vendor") &&
330             mSystemConfig.mGeneric.name != kDefaultThresholdName) {
331             mVendorConfig.mGeneric = mSystemConfig.mGeneric;
332             mVendorConfig.mGeneric.name = toString(ComponentType::VENDOR);
333         }
334         mPackagesToAppCategoryMappingUpdateMode = OVERWRITE;
335     }
336     if (!updateFromXmlPerType(kLatestThirdPartyConfigXmlPath, "latest third-party")) {
337         if (!updateFromXmlPerType(kBuildThirdPartyConfigXmlPath, "build third-party") &&
338             mSystemConfig.mGeneric.name != kDefaultThresholdName) {
339             mThirdPartyConfig.mGeneric = mSystemConfig.mGeneric;
340             mThirdPartyConfig.mGeneric.name = toString(ComponentType::THIRD_PARTY);
341         }
342     }
343 }
344 
operator ()(const IoOveruseAlertThreshold & threshold) const345 size_t IoOveruseConfigs::AlertThresholdHashByDuration::operator()(
346         const IoOveruseAlertThreshold& threshold) const {
347     return std::hash<std::string>{}(std::to_string(threshold.durationInSeconds));
348 }
349 
operator ()(const IoOveruseAlertThreshold & l,const IoOveruseAlertThreshold & r) const350 bool IoOveruseConfigs::AlertThresholdEqualByDuration::operator()(
351         const IoOveruseAlertThreshold& l, const IoOveruseAlertThreshold& r) const {
352     return l.durationInSeconds == r.durationInSeconds;
353 }
354 
updatePerCategoryThresholds(const std::vector<PerStateIoOveruseThreshold> & thresholds)355 Result<void> IoOveruseConfigs::updatePerCategoryThresholds(
356         const std::vector<PerStateIoOveruseThreshold>& thresholds) {
357     mPerCategoryThresholds.clear();
358     if (thresholds.empty()) {
359         return Error() << "\tNo per-category thresholds provided so clearing it\n";
360     }
361     std::string errorMsgs;
362     for (const auto& categoryThreshold : thresholds) {
363         if (auto result = containsValidThresholds(categoryThreshold); !result.ok()) {
364             StringAppendF(&errorMsgs, "\tInvalid category specific thresholds: '%s'\n",
365                           result.error().message().c_str());
366             continue;
367         }
368         if (auto category = toApplicationCategoryType(categoryThreshold.name);
369             category == ApplicationCategoryType::OTHERS) {
370             StringAppendF(&errorMsgs, "\tInvalid application category '%s'\n",
371                           categoryThreshold.name.c_str());
372         } else {
373             if (const auto& it = mPerCategoryThresholds.find(category);
374                 it != mPerCategoryThresholds.end()) {
375                 StringAppendF(&errorMsgs, "\tDuplicate threshold received for category: '%s'\n",
376                               categoryThreshold.name.c_str());
377             }
378             mPerCategoryThresholds[category] = categoryThreshold;
379         }
380     }
381     return errorMsgs.empty() ? Result<void>{} : Error() << errorMsgs;
382 }
383 
updateAlertThresholds(const std::vector<IoOveruseAlertThreshold> & thresholds)384 Result<void> IoOveruseConfigs::updateAlertThresholds(
385         const std::vector<IoOveruseAlertThreshold>& thresholds) {
386     mAlertThresholds.clear();
387     std::string errorMsgs;
388     for (const auto& alertThreshold : thresholds) {
389         if (auto result = containsValidThreshold(alertThreshold); !result.ok()) {
390             StringAppendF(&errorMsgs, "\tInvalid system-wide alert threshold: %s\n",
391                           result.error().message().c_str());
392             continue;
393         }
394         if (const auto& it = mAlertThresholds.find(alertThreshold); it != mAlertThresholds.end()) {
395             StringAppendF(&errorMsgs,
396                           "\tDuplicate threshold received for duration %" PRId64
397                           ". Overwriting previous threshold with %" PRId64
398                           " written bytes per second \n",
399                           alertThreshold.durationInSeconds, it->writtenBytesPerSecond);
400         }
401         mAlertThresholds.emplace(alertThreshold);
402     }
403     return errorMsgs.empty() ? Result<void>{} : Error() << errorMsgs;
404 }
405 
update(const std::vector<ResourceOveruseConfiguration> & resourceOveruseConfigs)406 Result<void> IoOveruseConfigs::update(
407         const std::vector<ResourceOveruseConfiguration>& resourceOveruseConfigs) {
408     if (const auto result = isValidResourceOveruseConfigs(resourceOveruseConfigs); !result.ok()) {
409         return Error(EX_ILLEGAL_ARGUMENT) << result.error();
410     }
411     for (const auto& resourceOveruseConfig : resourceOveruseConfigs) {
412         updateFromAidlConfig(resourceOveruseConfig);
413     }
414     return {};
415 }
416 
updateFromXml(const char * filename)417 Result<void> IoOveruseConfigs::updateFromXml(const char* filename) {
418     const auto resourceOveruseConfig = sParseXmlFile(filename);
419     if (!resourceOveruseConfig.ok()) {
420         return Error() << "Failed to parse configuration: " << resourceOveruseConfig.error();
421     }
422     if (const auto result = isValidResourceOveruseConfig(*resourceOveruseConfig); !result.ok()) {
423         return result;
424     }
425     updateFromAidlConfig(*resourceOveruseConfig);
426     return {};
427 }
428 
updateFromAidlConfig(const ResourceOveruseConfiguration & resourceOveruseConfig)429 void IoOveruseConfigs::updateFromAidlConfig(
430         const ResourceOveruseConfiguration& resourceOveruseConfig) {
431     ComponentSpecificConfig* targetComponentConfig;
432     int32_t updatableConfigsFilter = 0;
433     switch (resourceOveruseConfig.componentType) {
434         case ComponentType::SYSTEM:
435             targetComponentConfig = &mSystemConfig;
436             updatableConfigsFilter = kSystemComponentUpdatableConfigs;
437             break;
438         case ComponentType::VENDOR:
439             targetComponentConfig = &mVendorConfig;
440             updatableConfigsFilter = kVendorComponentUpdatableConfigs;
441             break;
442         case ComponentType::THIRD_PARTY:
443             targetComponentConfig = &mThirdPartyConfig;
444             updatableConfigsFilter = kThirdPartyComponentUpdatableConfigs;
445             break;
446         default:
447             // This case shouldn't execute as it is caught during validation.
448             return;
449     }
450 
451     const std::string componentTypeStr = toString(resourceOveruseConfig.componentType);
452     for (const auto& resourceSpecificConfig :
453          resourceOveruseConfig.resourceSpecificConfigurations) {
454         /*
455          * |resourceSpecificConfig| should contain only ioOveruseConfiguration as it is verified
456          * during validation.
457          */
458         const auto& ioOveruseConfig =
459                 resourceSpecificConfig.get<ResourceSpecificConfiguration::ioOveruseConfiguration>();
460         if (auto res = update(resourceOveruseConfig, ioOveruseConfig, updatableConfigsFilter,
461                               targetComponentConfig);
462             !res.ok()) {
463             ALOGE("Ignorable I/O overuse configuration errors for '%s' component:\n%s",
464                   componentTypeStr.c_str(), res.error().message().c_str());
465         }
466     }
467     return;
468 }
469 
update(const ResourceOveruseConfiguration & resourceOveruseConfiguration,const IoOveruseConfiguration & ioOveruseConfiguration,int32_t updatableConfigsFilter,ComponentSpecificConfig * targetComponentConfig)470 Result<void> IoOveruseConfigs::update(
471         const ResourceOveruseConfiguration& resourceOveruseConfiguration,
472         const IoOveruseConfiguration& ioOveruseConfiguration, int32_t updatableConfigsFilter,
473         ComponentSpecificConfig* targetComponentConfig) {
474     if ((updatableConfigsFilter & OveruseConfigEnum::COMPONENT_SPECIFIC_GENERIC_THRESHOLDS)) {
475         targetComponentConfig->mGeneric = ioOveruseConfiguration.componentLevelThresholds;
476     }
477 
478     std::string nonUpdatableConfigMsgs;
479     if (updatableConfigsFilter & OveruseConfigEnum::VENDOR_PACKAGE_PREFIXES) {
480         mVendorPackagePrefixes.clear();
481         for (const auto& prefix : resourceOveruseConfiguration.vendorPackagePrefixes) {
482             if (!prefix.empty()) {
483                 mVendorPackagePrefixes.insert(prefix);
484             }
485         }
486     } else if (!resourceOveruseConfiguration.vendorPackagePrefixes.empty()) {
487         StringAppendF(&nonUpdatableConfigMsgs, "%svendor packages prefixes",
488                       !nonUpdatableConfigMsgs.empty() ? ", " : "");
489     }
490 
491     if (updatableConfigsFilter & OveruseConfigEnum::PACKAGE_APP_CATEGORY_MAPPINGS) {
492         if (mPackagesToAppCategoryMappingUpdateMode == OVERWRITE) {
493             mPackagesToAppCategories.clear();
494         }
495         if (mPackagesToAppCategoryMappingUpdateMode != NO_UPDATE) {
496             for (const auto& meta : resourceOveruseConfiguration.packageMetadata) {
497                 if (!meta.packageName.empty()) {
498                     mPackagesToAppCategories[meta.packageName] = meta.appCategoryType;
499                 }
500             }
501         }
502     } else if (!resourceOveruseConfiguration.packageMetadata.empty()) {
503         StringAppendF(&nonUpdatableConfigMsgs, "%spackage to application category mappings",
504                       !nonUpdatableConfigMsgs.empty() ? ", " : "");
505     }
506 
507     std::string errorMsgs;
508     const auto maybeAppendVendorPackagePrefixes =
509             [&componentType = std::as_const(resourceOveruseConfiguration.componentType),
510              &vendorPackagePrefixes = mVendorPackagePrefixes](const std::string& packageName) {
511                 if (componentType != ComponentType::VENDOR) {
512                     return;
513                 }
514                 for (const auto& prefix : vendorPackagePrefixes) {
515                     if (StartsWith(packageName, prefix)) {
516                         return;
517                     }
518                 }
519                 vendorPackagePrefixes.insert(packageName);
520             };
521 
522     if (updatableConfigsFilter & OveruseConfigEnum::COMPONENT_SPECIFIC_PER_PACKAGE_THRESHOLDS) {
523         if (auto result = targetComponentConfig
524                                   ->updatePerPackageThresholds(ioOveruseConfiguration
525                                                                        .packageSpecificThresholds,
526                                                                maybeAppendVendorPackagePrefixes);
527             !result.ok()) {
528             StringAppendF(&errorMsgs, "\t\t%s", result.error().message().c_str());
529         }
530     } else if (!ioOveruseConfiguration.packageSpecificThresholds.empty()) {
531         StringAppendF(&nonUpdatableConfigMsgs, "%sper-package thresholds",
532                       !nonUpdatableConfigMsgs.empty() ? ", " : "");
533     }
534 
535     if (updatableConfigsFilter & OveruseConfigEnum::COMPONENT_SPECIFIC_SAFE_TO_KILL_PACKAGES) {
536         if (auto result = targetComponentConfig
537                                   ->updateSafeToKillPackages(resourceOveruseConfiguration
538                                                                      .safeToKillPackages,
539                                                              maybeAppendVendorPackagePrefixes);
540             !result.ok()) {
541             StringAppendF(&errorMsgs, "%s\t\t%s", !errorMsgs.empty() ? "\n" : "",
542                           result.error().message().c_str());
543         }
544     } else if (!resourceOveruseConfiguration.safeToKillPackages.empty()) {
545         StringAppendF(&nonUpdatableConfigMsgs, "%ssafe-to-kill list",
546                       !nonUpdatableConfigMsgs.empty() ? ", " : "");
547     }
548 
549     if (updatableConfigsFilter & OveruseConfigEnum::PER_CATEGORY_THRESHOLDS) {
550         if (auto result =
551                     updatePerCategoryThresholds(ioOveruseConfiguration.categorySpecificThresholds);
552             !result.ok()) {
553             StringAppendF(&errorMsgs, "%s\t\t%s", !errorMsgs.empty() ? "\n" : "",
554                           result.error().message().c_str());
555         }
556     } else if (!ioOveruseConfiguration.categorySpecificThresholds.empty()) {
557         StringAppendF(&nonUpdatableConfigMsgs, "%scategory specific thresholds",
558                       !nonUpdatableConfigMsgs.empty() ? ", " : "");
559     }
560 
561     if (updatableConfigsFilter & OveruseConfigEnum::SYSTEM_WIDE_ALERT_THRESHOLDS) {
562         if (auto result = updateAlertThresholds(ioOveruseConfiguration.systemWideThresholds);
563             !result.ok()) {
564             StringAppendF(&errorMsgs, "%s\t\t%s", !errorMsgs.empty() ? "\n" : "",
565                           result.error().message().c_str());
566         }
567     } else if (!ioOveruseConfiguration.systemWideThresholds.empty()) {
568         StringAppendF(&nonUpdatableConfigMsgs, "%ssystem-wide alert thresholds",
569                       !nonUpdatableConfigMsgs.empty() ? ", " : "");
570     }
571 
572     if (!nonUpdatableConfigMsgs.empty()) {
573         StringAppendF(&errorMsgs, "%s\t\tReceived values for non-updatable configs: [%s]",
574                       !errorMsgs.empty() ? "\n" : "", nonUpdatableConfigMsgs.c_str());
575     }
576     if (!errorMsgs.empty()) {
577         return Error() << errorMsgs.c_str();
578     }
579     return {};
580 }
581 
get(std::vector<ResourceOveruseConfiguration> * resourceOveruseConfigs) const582 void IoOveruseConfigs::get(
583         std::vector<ResourceOveruseConfiguration>* resourceOveruseConfigs) const {
584     auto systemConfig = get(mSystemConfig, kSystemComponentUpdatableConfigs);
585     if (systemConfig.has_value()) {
586         systemConfig->componentType = ComponentType::SYSTEM;
587         resourceOveruseConfigs->emplace_back(std::move(*systemConfig));
588     }
589 
590     auto vendorConfig = get(mVendorConfig, kVendorComponentUpdatableConfigs);
591     if (vendorConfig.has_value()) {
592         vendorConfig->componentType = ComponentType::VENDOR;
593         resourceOveruseConfigs->emplace_back(std::move(*vendorConfig));
594     }
595 
596     auto thirdPartyConfig = get(mThirdPartyConfig, kThirdPartyComponentUpdatableConfigs);
597     if (thirdPartyConfig.has_value()) {
598         thirdPartyConfig->componentType = ComponentType::THIRD_PARTY;
599         resourceOveruseConfigs->emplace_back(std::move(*thirdPartyConfig));
600     }
601 }
602 
get(const ComponentSpecificConfig & componentSpecificConfig,const int32_t componentFilter) const603 std::optional<ResourceOveruseConfiguration> IoOveruseConfigs::get(
604         const ComponentSpecificConfig& componentSpecificConfig,
605         const int32_t componentFilter) const {
606     if (componentSpecificConfig.mGeneric.name == kDefaultThresholdName) {
607         return {};
608     }
609     ResourceOveruseConfiguration resourceOveruseConfiguration;
610     IoOveruseConfiguration ioOveruseConfiguration;
611     if ((componentFilter & OveruseConfigEnum::COMPONENT_SPECIFIC_GENERIC_THRESHOLDS)) {
612         ioOveruseConfiguration.componentLevelThresholds = componentSpecificConfig.mGeneric;
613     }
614     if (componentFilter & OveruseConfigEnum::VENDOR_PACKAGE_PREFIXES) {
615         resourceOveruseConfiguration.vendorPackagePrefixes = toStringVector(mVendorPackagePrefixes);
616     }
617     if (componentFilter & OveruseConfigEnum::PACKAGE_APP_CATEGORY_MAPPINGS) {
618         for (const auto& [packageName, appCategoryType] : mPackagesToAppCategories) {
619             PackageMetadata meta;
620             meta.packageName = packageName;
621             meta.appCategoryType = appCategoryType;
622             resourceOveruseConfiguration.packageMetadata.push_back(meta);
623         }
624     }
625     if (componentFilter & OveruseConfigEnum::COMPONENT_SPECIFIC_PER_PACKAGE_THRESHOLDS) {
626         for (const auto& [packageName, threshold] : componentSpecificConfig.mPerPackageThresholds) {
627             ioOveruseConfiguration.packageSpecificThresholds.push_back(threshold);
628         }
629     }
630     if (componentFilter & OveruseConfigEnum::COMPONENT_SPECIFIC_SAFE_TO_KILL_PACKAGES) {
631         resourceOveruseConfiguration.safeToKillPackages =
632                 toStringVector(componentSpecificConfig.mSafeToKillPackages);
633     }
634     if (componentFilter & OveruseConfigEnum::PER_CATEGORY_THRESHOLDS) {
635         for (const auto& [category, threshold] : mPerCategoryThresholds) {
636             ioOveruseConfiguration.categorySpecificThresholds.push_back(threshold);
637         }
638     }
639     if (componentFilter & OveruseConfigEnum::SYSTEM_WIDE_ALERT_THRESHOLDS) {
640         for (const auto& threshold : mAlertThresholds) {
641             ioOveruseConfiguration.systemWideThresholds.push_back(threshold);
642         }
643     }
644     ResourceSpecificConfiguration resourceSpecificConfig;
645     resourceSpecificConfig.set<ResourceSpecificConfiguration::ioOveruseConfiguration>(
646             ioOveruseConfiguration);
647     resourceOveruseConfiguration.resourceSpecificConfigurations.emplace_back(
648             std::move(resourceSpecificConfig));
649     return resourceOveruseConfiguration;
650 }
651 
writeToDisk()652 Result<void> IoOveruseConfigs::writeToDisk() {
653     std::vector<ResourceOveruseConfiguration> resourceOveruseConfigs;
654     get(&resourceOveruseConfigs);
655     for (const auto resourceOveruseConfig : resourceOveruseConfigs) {
656         switch (resourceOveruseConfig.componentType) {
657             case ComponentType::SYSTEM:
658                 if (const auto result =
659                             sWriteXmlFile(resourceOveruseConfig, kLatestSystemConfigXmlPath);
660                     !result.ok()) {
661                     return Error() << "Failed to write system resource overuse config to disk";
662                 }
663                 continue;
664             case ComponentType::VENDOR:
665                 if (const auto result =
666                             sWriteXmlFile(resourceOveruseConfig, kLatestVendorConfigXmlPath);
667                     !result.ok()) {
668                     return Error() << "Failed to write vendor resource overuse config to disk";
669                 }
670                 continue;
671             case ComponentType::THIRD_PARTY:
672                 if (const auto result =
673                             sWriteXmlFile(resourceOveruseConfig, kLatestThirdPartyConfigXmlPath);
674                     !result.ok()) {
675                     return Error() << "Failed to write third-party resource overuse config to disk";
676                 }
677                 continue;
678             case ComponentType::UNKNOWN:
679                 continue;
680         }
681     }
682     return {};
683 }
684 
fetchThreshold(const PackageInfo & packageInfo) const685 PerStateBytes IoOveruseConfigs::fetchThreshold(const PackageInfo& packageInfo) const {
686     switch (packageInfo.componentType) {
687         case ComponentType::SYSTEM:
688             if (const auto it = mSystemConfig.mPerPackageThresholds.find(
689                         packageInfo.packageIdentifier.name);
690                 it != mSystemConfig.mPerPackageThresholds.end()) {
691                 return it->second.perStateWriteBytes;
692             }
693             if (const auto it = mPerCategoryThresholds.find(packageInfo.appCategoryType);
694                 it != mPerCategoryThresholds.end()) {
695                 return it->second.perStateWriteBytes;
696             }
697             return mSystemConfig.mGeneric.perStateWriteBytes;
698         case ComponentType::VENDOR:
699             if (const auto it = mVendorConfig.mPerPackageThresholds.find(
700                         packageInfo.packageIdentifier.name);
701                 it != mVendorConfig.mPerPackageThresholds.end()) {
702                 return it->second.perStateWriteBytes;
703             }
704             if (const auto it = mPerCategoryThresholds.find(packageInfo.appCategoryType);
705                 it != mPerCategoryThresholds.end()) {
706                 return it->second.perStateWriteBytes;
707             }
708             return mVendorConfig.mGeneric.perStateWriteBytes;
709         case ComponentType::THIRD_PARTY:
710             if (const auto it = mPerCategoryThresholds.find(packageInfo.appCategoryType);
711                 it != mPerCategoryThresholds.end()) {
712                 return it->second.perStateWriteBytes;
713             }
714             return mThirdPartyConfig.mGeneric.perStateWriteBytes;
715         default:
716             ALOGW("Returning default threshold for %s",
717                   packageInfo.packageIdentifier.toString().c_str());
718             return defaultThreshold().perStateWriteBytes;
719     }
720 }
721 
isSafeToKill(const PackageInfo & packageInfo) const722 bool IoOveruseConfigs::isSafeToKill(const PackageInfo& packageInfo) const {
723     if (packageInfo.uidType == UidType::NATIVE) {
724         // Native packages can't be disabled so don't kill them on I/O overuse.
725         return false;
726     }
727     switch (packageInfo.componentType) {
728         case ComponentType::SYSTEM:
729             if (mSystemConfig.mSafeToKillPackages.find(packageInfo.packageIdentifier.name) !=
730                 mSystemConfig.mSafeToKillPackages.end()) {
731                 return true;
732             }
733             return isSafeToKillAnyPackage(packageInfo.sharedUidPackages,
734                                           mSystemConfig.mSafeToKillPackages);
735         case ComponentType::VENDOR:
736             if (mVendorConfig.mSafeToKillPackages.find(packageInfo.packageIdentifier.name) !=
737                 mVendorConfig.mSafeToKillPackages.end()) {
738                 return true;
739             }
740             /*
741              * Packages under the vendor shared UID may contain system packages because when
742              * CarWatchdogService derives the shared component type it attributes system packages
743              * as vendor packages when there is at least one vendor package.
744              */
745             return isSafeToKillAnyPackage(packageInfo.sharedUidPackages,
746                                           mSystemConfig.mSafeToKillPackages) ||
747                     isSafeToKillAnyPackage(packageInfo.sharedUidPackages,
748                                            mVendorConfig.mSafeToKillPackages);
749         default:
750             return true;
751     }
752 }
753 
754 }  // namespace watchdog
755 }  // namespace automotive
756 }  // namespace android
757