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 ::android::automotive::watchdog::PerStateBytes;
37 using ::android::automotive::watchdog::internal::ApplicationCategoryType;
38 using ::android::automotive::watchdog::internal::ComponentType;
39 using ::android::automotive::watchdog::internal::IoOveruseAlertThreshold;
40 using ::android::automotive::watchdog::internal::IoOveruseConfiguration;
41 using ::android::automotive::watchdog::internal::PackageInfo;
42 using ::android::automotive::watchdog::internal::PackageMetadata;
43 using ::android::automotive::watchdog::internal::PerStateIoOveruseThreshold;
44 using ::android::automotive::watchdog::internal::ResourceOveruseConfiguration;
45 using ::android::automotive::watchdog::internal::ResourceSpecificConfiguration;
46 using ::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 using ::android::binder::Status;
53
54 namespace {
55
56 // Enum to filter the updatable overuse configs by each component.
57 enum OveruseConfigEnum {
58 COMPONENT_SPECIFIC_SAFE_TO_KILL_PACKAGES = 1 << 0,
59 VENDOR_PACKAGE_PREFIXES = 1 << 1,
60 PACKAGE_APP_CATEGORY_MAPPINGS = 1 << 2,
61 COMPONENT_SPECIFIC_GENERIC_THRESHOLDS = 1 << 3,
62 COMPONENT_SPECIFIC_PER_PACKAGE_THRESHOLDS = 1 << 4,
63 PER_CATEGORY_THRESHOLDS = 1 << 5,
64 SYSTEM_WIDE_ALERT_THRESHOLDS = 1 << 6,
65 };
66
67 const int32_t kSystemComponentUpdatableConfigs = COMPONENT_SPECIFIC_SAFE_TO_KILL_PACKAGES |
68 PACKAGE_APP_CATEGORY_MAPPINGS | COMPONENT_SPECIFIC_GENERIC_THRESHOLDS |
69 COMPONENT_SPECIFIC_PER_PACKAGE_THRESHOLDS | SYSTEM_WIDE_ALERT_THRESHOLDS;
70 const int32_t kVendorComponentUpdatableConfigs = COMPONENT_SPECIFIC_SAFE_TO_KILL_PACKAGES |
71 VENDOR_PACKAGE_PREFIXES | PACKAGE_APP_CATEGORY_MAPPINGS |
72 COMPONENT_SPECIFIC_GENERIC_THRESHOLDS | COMPONENT_SPECIFIC_PER_PACKAGE_THRESHOLDS |
73 PER_CATEGORY_THRESHOLDS;
74 const int32_t kThirdPartyComponentUpdatableConfigs = COMPONENT_SPECIFIC_GENERIC_THRESHOLDS;
75
toStringVector(const std::unordered_set<std::string> & values)76 const std::vector<std::string> toStringVector(const std::unordered_set<std::string>& values) {
77 std::vector<std::string> output;
78 for (const auto& v : values) {
79 if (!v.empty()) {
80 output.emplace_back(v);
81 }
82 }
83 return output;
84 }
85
isZeroValueThresholds(const PerStateIoOveruseThreshold & thresholds)86 bool isZeroValueThresholds(const PerStateIoOveruseThreshold& thresholds) {
87 return thresholds.perStateWriteBytes.foregroundBytes == 0 &&
88 thresholds.perStateWriteBytes.backgroundBytes == 0 &&
89 thresholds.perStateWriteBytes.garageModeBytes == 0;
90 }
91
toString(const PerStateIoOveruseThreshold & thresholds)92 std::string toString(const PerStateIoOveruseThreshold& thresholds) {
93 return StringPrintf("name=%s, foregroundBytes=%" PRId64 ", backgroundBytes=%" PRId64
94 ", garageModeBytes=%" PRId64,
95 thresholds.name.c_str(), thresholds.perStateWriteBytes.foregroundBytes,
96 thresholds.perStateWriteBytes.backgroundBytes,
97 thresholds.perStateWriteBytes.garageModeBytes);
98 }
99
containsValidThresholds(const PerStateIoOveruseThreshold & thresholds)100 Result<void> containsValidThresholds(const PerStateIoOveruseThreshold& thresholds) {
101 if (thresholds.name.empty()) {
102 return Error() << "Doesn't contain threshold name";
103 }
104
105 if (isZeroValueThresholds(thresholds)) {
106 return Error() << "Zero value thresholds for " << thresholds.name;
107 }
108
109 if (thresholds.perStateWriteBytes.foregroundBytes == 0 ||
110 thresholds.perStateWriteBytes.backgroundBytes == 0 ||
111 thresholds.perStateWriteBytes.garageModeBytes == 0) {
112 return Error() << "Some thresholds are zero: " << toString(thresholds);
113 }
114 return {};
115 }
116
containsValidThreshold(const IoOveruseAlertThreshold & threshold)117 Result<void> containsValidThreshold(const IoOveruseAlertThreshold& threshold) {
118 if (threshold.durationInSeconds == 0) {
119 return Error() << "Duration must be greater than zero";
120 }
121 if (threshold.writtenBytesPerSecond == 0) {
122 return Error() << "Written bytes/second must be greater than zero";
123 }
124 return {};
125 }
126
toApplicationCategoryType(const std::string & value)127 ApplicationCategoryType toApplicationCategoryType(const std::string& value) {
128 if (value == "MAPS") {
129 return ApplicationCategoryType::MAPS;
130 }
131 if (value == "MEDIA") {
132 return ApplicationCategoryType::MEDIA;
133 }
134 return ApplicationCategoryType::OTHERS;
135 }
136
isValidIoOveruseConfiguration(const ComponentType componentType,const int32_t updatableConfigsFilter,const IoOveruseConfiguration & ioOveruseConfig)137 Result<void> isValidIoOveruseConfiguration(const ComponentType componentType,
138 const int32_t updatableConfigsFilter,
139 const IoOveruseConfiguration& ioOveruseConfig) {
140 auto componentTypeStr = toString(componentType);
141 if (updatableConfigsFilter & OveruseConfigEnum::COMPONENT_SPECIFIC_GENERIC_THRESHOLDS) {
142 if (auto result = containsValidThresholds(ioOveruseConfig.componentLevelThresholds);
143 !result.ok()) {
144 return Error() << "Invalid " << toString(componentType)
145 << " component level generic thresholds: " << result.error();
146 }
147 if (ioOveruseConfig.componentLevelThresholds.name != componentTypeStr) {
148 return Error() << "Invalid component name "
149 << ioOveruseConfig.componentLevelThresholds.name
150 << " in component level generic thresholds for component "
151 << componentTypeStr;
152 }
153 }
154 const auto containsValidSystemWideThresholds = [&]() -> bool {
155 if (ioOveruseConfig.systemWideThresholds.empty()) {
156 return false;
157 }
158 for (const auto& threshold : ioOveruseConfig.systemWideThresholds) {
159 if (auto result = containsValidThreshold(threshold); !result.ok()) {
160 return false;
161 }
162 }
163 return true;
164 };
165 if ((updatableConfigsFilter & OveruseConfigEnum::SYSTEM_WIDE_ALERT_THRESHOLDS) &&
166 !containsValidSystemWideThresholds()) {
167 return Error() << "Invalid system-wide alert threshold provided in " << componentTypeStr
168 << " config";
169 }
170 return {};
171 }
172
getComponentFilter(const ComponentType componentType)173 Result<int32_t> getComponentFilter(const ComponentType componentType) {
174 switch (componentType) {
175 case ComponentType::SYSTEM:
176 return kSystemComponentUpdatableConfigs;
177 case ComponentType::VENDOR:
178 return kVendorComponentUpdatableConfigs;
179 case ComponentType::THIRD_PARTY:
180 return kThirdPartyComponentUpdatableConfigs;
181 default:
182 return Error() << "Invalid component type: " << static_cast<int32_t>(componentType);
183 }
184 }
185
isValidResourceOveruseConfig(const ResourceOveruseConfiguration & resourceOveruseConfig)186 Result<void> isValidResourceOveruseConfig(
187 const ResourceOveruseConfiguration& resourceOveruseConfig) {
188 const auto filter = getComponentFilter(resourceOveruseConfig.componentType);
189 if (!filter.ok()) {
190 return Error() << filter.error();
191 }
192 std::unordered_map<std::string, ApplicationCategoryType> seenCategoryMappings;
193 for (const auto& meta : resourceOveruseConfig.packageMetadata) {
194 if (const auto it = seenCategoryMappings.find(meta.packageName);
195 it != seenCategoryMappings.end() && it->second != meta.appCategoryType) {
196 return Error()
197 << "Must provide exactly one application category mapping for the package "
198 << meta.packageName << ": Provided mappings " << toString(meta.appCategoryType)
199 << " and " << toString(it->second);
200 }
201 seenCategoryMappings[meta.packageName] = meta.appCategoryType;
202 }
203 if (resourceOveruseConfig.resourceSpecificConfigurations.size() != 1) {
204 return Error() << "Must provide exactly one I/O overuse configuration. Received "
205 << resourceOveruseConfig.resourceSpecificConfigurations.size()
206 << " configurations";
207 }
208 for (const auto& config : resourceOveruseConfig.resourceSpecificConfigurations) {
209 if (config.getTag() != ResourceSpecificConfiguration::ioOveruseConfiguration) {
210 return Error() << "Invalid resource type: " << config.getTag();
211 }
212 const auto& ioOveruseConfig =
213 config.get<ResourceSpecificConfiguration::ioOveruseConfiguration>();
214 if (auto result = isValidIoOveruseConfiguration(resourceOveruseConfig.componentType,
215 *filter, ioOveruseConfig);
216 !result.ok()) {
217 return Error() << "Invalid I/O overuse configuration for component "
218 << toString(resourceOveruseConfig.componentType).c_str() << ": "
219 << result.error();
220 }
221 }
222 return {};
223 }
224
isValidResourceOveruseConfigs(const std::vector<ResourceOveruseConfiguration> & resourceOveruseConfigs)225 Result<void> isValidResourceOveruseConfigs(
226 const std::vector<ResourceOveruseConfiguration>& resourceOveruseConfigs) {
227 std::unordered_set<ComponentType> seenComponentTypes;
228 for (const auto& resourceOveruseConfig : resourceOveruseConfigs) {
229 if (seenComponentTypes.count(resourceOveruseConfig.componentType) > 0) {
230 return Error() << "Cannot provide duplicate configs for the same component type "
231 << toString(resourceOveruseConfig.componentType);
232 }
233 if (const auto result = isValidResourceOveruseConfig(resourceOveruseConfig); !result.ok()) {
234 return result;
235 }
236 seenComponentTypes.insert(resourceOveruseConfig.componentType);
237 }
238 return {};
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({}) {
__anon129d16f60302(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(Status::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)582 void IoOveruseConfigs::get(std::vector<ResourceOveruseConfiguration>* resourceOveruseConfigs) {
583 auto systemConfig = get(mSystemConfig, kSystemComponentUpdatableConfigs);
584 if (systemConfig.has_value()) {
585 systemConfig->componentType = ComponentType::SYSTEM;
586 resourceOveruseConfigs->emplace_back(std::move(*systemConfig));
587 }
588
589 auto vendorConfig = get(mVendorConfig, kVendorComponentUpdatableConfigs);
590 if (vendorConfig.has_value()) {
591 vendorConfig->componentType = ComponentType::VENDOR;
592 resourceOveruseConfigs->emplace_back(std::move(*vendorConfig));
593 }
594
595 auto thirdPartyConfig = get(mThirdPartyConfig, kThirdPartyComponentUpdatableConfigs);
596 if (thirdPartyConfig.has_value()) {
597 thirdPartyConfig->componentType = ComponentType::THIRD_PARTY;
598 resourceOveruseConfigs->emplace_back(std::move(*thirdPartyConfig));
599 }
600 }
601
get(const ComponentSpecificConfig & componentSpecificConfig,const int32_t componentFilter)602 std::optional<ResourceOveruseConfiguration> IoOveruseConfigs::get(
603 const ComponentSpecificConfig& componentSpecificConfig, const int32_t componentFilter) {
604 if (componentSpecificConfig.mGeneric.name == kDefaultThresholdName) {
605 return {};
606 }
607 ResourceOveruseConfiguration resourceOveruseConfiguration;
608 IoOveruseConfiguration ioOveruseConfiguration;
609 if ((componentFilter & OveruseConfigEnum::COMPONENT_SPECIFIC_GENERIC_THRESHOLDS)) {
610 ioOveruseConfiguration.componentLevelThresholds = componentSpecificConfig.mGeneric;
611 }
612 if (componentFilter & OveruseConfigEnum::VENDOR_PACKAGE_PREFIXES) {
613 resourceOveruseConfiguration.vendorPackagePrefixes = toStringVector(mVendorPackagePrefixes);
614 }
615 if (componentFilter & OveruseConfigEnum::PACKAGE_APP_CATEGORY_MAPPINGS) {
616 for (const auto& [packageName, appCategoryType] : mPackagesToAppCategories) {
617 PackageMetadata meta;
618 meta.packageName = packageName;
619 meta.appCategoryType = appCategoryType;
620 resourceOveruseConfiguration.packageMetadata.push_back(meta);
621 }
622 }
623 if (componentFilter & OveruseConfigEnum::COMPONENT_SPECIFIC_PER_PACKAGE_THRESHOLDS) {
624 for (const auto& [packageName, threshold] : componentSpecificConfig.mPerPackageThresholds) {
625 ioOveruseConfiguration.packageSpecificThresholds.push_back(threshold);
626 }
627 }
628 if (componentFilter & OveruseConfigEnum::COMPONENT_SPECIFIC_SAFE_TO_KILL_PACKAGES) {
629 resourceOveruseConfiguration.safeToKillPackages =
630 toStringVector(componentSpecificConfig.mSafeToKillPackages);
631 }
632 if (componentFilter & OveruseConfigEnum::PER_CATEGORY_THRESHOLDS) {
633 for (const auto& [category, threshold] : mPerCategoryThresholds) {
634 ioOveruseConfiguration.categorySpecificThresholds.push_back(threshold);
635 }
636 }
637 if (componentFilter & OveruseConfigEnum::SYSTEM_WIDE_ALERT_THRESHOLDS) {
638 for (const auto& threshold : mAlertThresholds) {
639 ioOveruseConfiguration.systemWideThresholds.push_back(threshold);
640 }
641 }
642 ResourceSpecificConfiguration resourceSpecificConfig;
643 resourceSpecificConfig.set<ResourceSpecificConfiguration::ioOveruseConfiguration>(
644 ioOveruseConfiguration);
645 resourceOveruseConfiguration.resourceSpecificConfigurations.emplace_back(
646 std::move(resourceSpecificConfig));
647 return resourceOveruseConfiguration;
648 }
649
writeToDisk()650 Result<void> IoOveruseConfigs::writeToDisk() {
651 std::vector<ResourceOveruseConfiguration> resourceOveruseConfigs;
652 get(&resourceOveruseConfigs);
653 for (const auto resourceOveruseConfig : resourceOveruseConfigs) {
654 switch (resourceOveruseConfig.componentType) {
655 case ComponentType::SYSTEM:
656 if (const auto result =
657 sWriteXmlFile(resourceOveruseConfig, kLatestSystemConfigXmlPath);
658 !result.ok()) {
659 return Error() << "Failed to write system resource overuse config to disk";
660 }
661 continue;
662 case ComponentType::VENDOR:
663 if (const auto result =
664 sWriteXmlFile(resourceOveruseConfig, kLatestVendorConfigXmlPath);
665 !result.ok()) {
666 return Error() << "Failed to write vendor resource overuse config to disk";
667 }
668 continue;
669 case ComponentType::THIRD_PARTY:
670 if (const auto result =
671 sWriteXmlFile(resourceOveruseConfig, kLatestThirdPartyConfigXmlPath);
672 !result.ok()) {
673 return Error() << "Failed to write third-party resource overuse config to disk";
674 }
675 continue;
676 case ComponentType::UNKNOWN:
677 continue;
678 }
679 }
680 return {};
681 }
682
fetchThreshold(const PackageInfo & packageInfo) const683 PerStateBytes IoOveruseConfigs::fetchThreshold(const PackageInfo& packageInfo) const {
684 switch (packageInfo.componentType) {
685 case ComponentType::SYSTEM:
686 if (const auto it = mSystemConfig.mPerPackageThresholds.find(
687 packageInfo.packageIdentifier.name);
688 it != mSystemConfig.mPerPackageThresholds.end()) {
689 return it->second.perStateWriteBytes;
690 }
691 if (const auto it = mPerCategoryThresholds.find(packageInfo.appCategoryType);
692 it != mPerCategoryThresholds.end()) {
693 return it->second.perStateWriteBytes;
694 }
695 return mSystemConfig.mGeneric.perStateWriteBytes;
696 case ComponentType::VENDOR:
697 if (const auto it = mVendorConfig.mPerPackageThresholds.find(
698 packageInfo.packageIdentifier.name);
699 it != mVendorConfig.mPerPackageThresholds.end()) {
700 return it->second.perStateWriteBytes;
701 }
702 if (const auto it = mPerCategoryThresholds.find(packageInfo.appCategoryType);
703 it != mPerCategoryThresholds.end()) {
704 return it->second.perStateWriteBytes;
705 }
706 return mVendorConfig.mGeneric.perStateWriteBytes;
707 case ComponentType::THIRD_PARTY:
708 if (const auto it = mPerCategoryThresholds.find(packageInfo.appCategoryType);
709 it != mPerCategoryThresholds.end()) {
710 return it->second.perStateWriteBytes;
711 }
712 return mThirdPartyConfig.mGeneric.perStateWriteBytes;
713 default:
714 ALOGW("Returning default threshold for %s",
715 packageInfo.packageIdentifier.toString().c_str());
716 return defaultThreshold().perStateWriteBytes;
717 }
718 }
719
isSafeToKill(const PackageInfo & packageInfo) const720 bool IoOveruseConfigs::isSafeToKill(const PackageInfo& packageInfo) const {
721 if (packageInfo.uidType == UidType::NATIVE) {
722 // Native packages can't be disabled so don't kill them on I/O overuse.
723 return false;
724 }
725 switch (packageInfo.componentType) {
726 case ComponentType::SYSTEM:
727 return mSystemConfig.mSafeToKillPackages.find(packageInfo.packageIdentifier.name) !=
728 mSystemConfig.mSafeToKillPackages.end();
729 case ComponentType::VENDOR:
730 return mVendorConfig.mSafeToKillPackages.find(packageInfo.packageIdentifier.name) !=
731 mVendorConfig.mSafeToKillPackages.end();
732 default:
733 return true;
734 }
735 }
736
737 } // namespace watchdog
738 } // namespace automotive
739 } // namespace android
740