1 /*
2  * Copyright (C) 2017 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 ATRACE_TAG ATRACE_TAG_PACKAGE_MANAGER
18 
19 #include "CacheTracker.h"
20 
21 #include <fts.h>
22 #include <sys/xattr.h>
23 #include <utils/Trace.h>
24 
25 #include <android-base/logging.h>
26 #include <android-base/stringprintf.h>
27 
28 #include "QuotaUtils.h"
29 #include "utils.h"
30 
31 using android::base::StringPrintf;
32 
33 namespace android {
34 namespace installd {
35 
CacheTracker(userid_t userId,appid_t appId,const std::string & uuid)36 CacheTracker::CacheTracker(userid_t userId, appid_t appId, const std::string& uuid)
37       : cacheUsed(0),
38         cacheQuota(0),
39         mUserId(userId),
40         mAppId(appId),
41         mItemsLoaded(false),
42         mUuid(uuid) {
43 }
44 
~CacheTracker()45 CacheTracker::~CacheTracker() {
46 }
47 
toString()48 std::string CacheTracker::toString() {
49     return StringPrintf("UID=%d used=%" PRId64 " quota=%" PRId64 " ratio=%d",
50             multiuser_get_uid(mUserId, mAppId), cacheUsed, cacheQuota, getCacheRatio());
51 }
52 
addDataPath(const std::string & dataPath)53 void CacheTracker::addDataPath(const std::string& dataPath) {
54     mDataPaths.push_back(dataPath);
55 }
56 
loadStats()57 void CacheTracker::loadStats() {
58     ATRACE_BEGIN("loadStats quota");
59     cacheUsed = 0;
60     if (loadQuotaStats()) {
61         return;
62     }
63     ATRACE_END();
64 
65     ATRACE_BEGIN("loadStats tree");
66     cacheUsed = 0;
67     for (const auto& path : mDataPaths) {
68         auto cachePath = read_path_inode(path, "cache", kXattrInodeCache);
69         auto codeCachePath = read_path_inode(path, "code_cache", kXattrInodeCodeCache);
70         calculate_tree_size(cachePath, &cacheUsed);
71         calculate_tree_size(codeCachePath, &cacheUsed);
72     }
73     ATRACE_END();
74 }
75 
loadQuotaStats()76 bool CacheTracker::loadQuotaStats() {
77     int cacheGid = multiuser_get_cache_gid(mUserId, mAppId);
78     if (IsQuotaSupported(mUuid) && cacheGid != -1) {
79         int64_t space;
80         if ((space = GetOccupiedSpaceForGid(mUuid, cacheGid)) != -1) {
81             cacheUsed += space;
82         } else {
83             return false;
84         }
85 
86         if ((space = get_occupied_app_cache_space_external(mUuid, mUserId, mAppId)) != -1) {
87             cacheUsed += space;
88         } else {
89             return false;
90         }
91         return true;
92     } else {
93         return false;
94     }
95 }
96 
loadItemsFrom(const std::string & path)97 void CacheTracker::loadItemsFrom(const std::string& path) {
98     FTS *fts;
99     FTSENT *p;
100     char *argv[] = { (char*) path.c_str(), nullptr };
101     if (!(fts = fts_open(argv, FTS_PHYSICAL | FTS_NOCHDIR | FTS_XDEV, nullptr))) {
102         PLOG(WARNING) << "Failed to fts_open " << path;
103         return;
104     }
105     while ((p = fts_read(fts)) != nullptr) {
106         if (p->fts_level == 0) continue;
107 
108         // Create tracking nodes for everything we encounter
109         switch (p->fts_info) {
110         case FTS_D:
111         case FTS_DEFAULT:
112         case FTS_F:
113         case FTS_SL:
114         case FTS_SLNONE: {
115             auto item = std::shared_ptr<CacheItem>(new CacheItem(p));
116             p->fts_pointer = static_cast<void*>(item.get());
117             items.push_back(item);
118         }
119         }
120 
121         switch (p->fts_info) {
122         case FTS_D: {
123             auto item = static_cast<CacheItem*>(p->fts_pointer);
124             item->group |= (getxattr(p->fts_path, kXattrCacheGroup, nullptr, 0) >= 0);
125             item->tombstone |= (getxattr(p->fts_path, kXattrCacheTombstone, nullptr, 0) >= 0);
126 
127             // When group, immediately collect all files under tree
128             if (item->group) {
129                 while ((p = fts_read(fts)) != nullptr) {
130                     if (p->fts_info == FTS_DP && p->fts_level == item->level) break;
131                     switch (p->fts_info) {
132                     case FTS_D:
133                     case FTS_DEFAULT:
134                     case FTS_F:
135                     case FTS_SL:
136                     case FTS_SLNONE:
137                         item->size += p->fts_statp->st_blocks * 512;
138                         item->modified = std::max(item->modified, p->fts_statp->st_mtime);
139                     }
140                 }
141             }
142         }
143         }
144 
145         // Bubble up modified time to parent
146         CHECK(p != nullptr);
147         switch (p->fts_info) {
148         case FTS_DP:
149         case FTS_DEFAULT:
150         case FTS_F:
151         case FTS_SL:
152         case FTS_SLNONE: {
153             auto item = static_cast<CacheItem*>(p->fts_pointer);
154             auto parent = static_cast<CacheItem*>(p->fts_parent->fts_pointer);
155             if (parent) {
156                 parent->modified = std::max(parent->modified, item->modified);
157             }
158         }
159         }
160     }
161     fts_close(fts);
162 }
163 
loadItems()164 void CacheTracker::loadItems() {
165     items.clear();
166 
167     ATRACE_BEGIN("loadItems");
168     for (const auto& path : mDataPaths) {
169         loadItemsFrom(read_path_inode(path, "cache", kXattrInodeCache));
170         loadItemsFrom(read_path_inode(path, "code_cache", kXattrInodeCodeCache));
171     }
172     ATRACE_END();
173 
174     ATRACE_BEGIN("sortItems");
175     auto cmp = [](std::shared_ptr<CacheItem> left, std::shared_ptr<CacheItem> right) {
176         // TODO: sort dotfiles last
177         // TODO: sort code_cache last
178         if (left->modified != right->modified) {
179             return (left->modified > right->modified);
180         }
181         if (left->level != right->level) {
182             return (left->level < right->level);
183         }
184         return left->directory;
185     };
186     std::stable_sort(items.begin(), items.end(), cmp);
187     ATRACE_END();
188 }
189 
ensureItems()190 void CacheTracker::ensureItems() {
191     if (mItemsLoaded) {
192         return;
193     } else {
194         loadItems();
195         mItemsLoaded = true;
196     }
197 }
198 
getCacheRatio()199 int CacheTracker::getCacheRatio() {
200     if (cacheQuota == 0) {
201         return 0;
202     } else {
203         return (cacheUsed * 10000) / cacheQuota;
204     }
205 }
206 
207 }  // namespace installd
208 }  // namespace android
209