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