1 // Copyright (C) 2020 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 #include "maintenance/db_cleaner.h"
16
17 #include <android-base/file.h>
18
19 #include <cstdio>
20 #include <filesystem>
21 #include <fstream>
22 #include <iostream>
23 #include <limits>
24 #include <optional>
25 #include <string>
26 #include <vector>
27
28 #include "db/clean_up.h"
29 #include "db/file_models.h"
30 #include "db/models.h"
31
32 namespace iorap::maintenance {
33
34 // Enable foreign key restriction.
35 const constexpr char* kForeignKeyOnSql = "PRAGMA foreign_keys = ON;";
36
CleanUpDatabase(const db::DbHandle & db,std::shared_ptr<binder::PackageVersionMap> version_map)37 void CleanUpDatabase(const db::DbHandle& db,
38 std::shared_ptr<binder::PackageVersionMap> version_map) {
39 std::vector<db::PackageModel> packages = db::PackageModel::SelectAll(db);
40 // Enable cascade deletion.
41 if (!db::DbQueryBuilder::ExecuteOnce(db, kForeignKeyOnSql)) {
42 LOG(ERROR) << "Fail to turn on foreign key restraint!";
43 }
44
45 for (db::PackageModel package : packages) {
46 std::optional<int64_t> version = version_map->Find(package.name);
47 if (!version) {
48 LOG(DEBUG) << "Fail to find version for package " << package.name
49 << " with version " << package.version
50 << ". The package manager may be down.";
51 continue;
52 }
53 // Package is cleanup if it
54 // * is not in the version map, it may be uninstalled
55 // * has an different version with the latest one
56 if (*version != package.version) {
57 db::CleanUpFilesForPackage(db, package.id, package.name, package.version);
58 if (!package.Delete()) {
59 LOG(ERROR) << "Fail to delete package " << package.name
60 << " with version " << package.version;
61 }
62 }
63 }
64 }
65
66 } // namespace iorap::maintenance
67