blob: dbd97cfa039a4157f430439e3abb75105ccc2c19 [file] [log] [blame]
Songchun Fan3c82a302019-11-29 14:23:45 -08001/*
2 * Copyright (C) 2019 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 "IncrementalService"
18
19#include "IncrementalService.h"
20
21#include <android-base/file.h>
22#include <android-base/logging.h>
23#include <android-base/properties.h>
24#include <android-base/stringprintf.h>
25#include <android-base/strings.h>
26#include <android/content/pm/IDataLoaderStatusListener.h>
27#include <android/os/IVold.h>
28#include <androidfw/ZipFileRO.h>
29#include <androidfw/ZipUtils.h>
30#include <binder/BinderService.h>
31#include <binder/ParcelFileDescriptor.h>
32#include <binder/Status.h>
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080033#include <openssl/sha.h>
Songchun Fan3c82a302019-11-29 14:23:45 -080034#include <sys/stat.h>
35#include <uuid/uuid.h>
36#include <zlib.h>
37
Alex Buynytskyy18b07a42020-02-03 20:06:00 -080038#include <ctime>
Songchun Fan3c82a302019-11-29 14:23:45 -080039#include <iterator>
40#include <span>
41#include <stack>
42#include <thread>
43#include <type_traits>
44
45#include "Metadata.pb.h"
46
47using namespace std::literals;
48using namespace android::content::pm;
49
50namespace android::incremental {
51
52namespace {
53
54using IncrementalFileSystemControlParcel =
55 ::android::os::incremental::IncrementalFileSystemControlParcel;
56
57struct Constants {
58 static constexpr auto backing = "backing_store"sv;
59 static constexpr auto mount = "mount"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080060 static constexpr auto storagePrefix = "st"sv;
61 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
62 static constexpr auto infoMdName = ".info"sv;
63};
64
65static const Constants& constants() {
66 static Constants c;
67 return c;
68}
69
70template <base::LogSeverity level = base::ERROR>
71bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
72 auto cstr = path::c_str(name);
73 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080074 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -080075 PLOG(level) << "Can't create directory '" << name << '\'';
76 return false;
77 }
78 struct stat st;
79 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
80 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
81 return false;
82 }
83 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080084 if (::chmod(cstr, mode)) {
85 PLOG(level) << "Changing permission failed for '" << name << '\'';
86 return false;
87 }
88
Songchun Fan3c82a302019-11-29 14:23:45 -080089 return true;
90}
91
92static std::string toMountKey(std::string_view path) {
93 if (path.empty()) {
94 return "@none";
95 }
96 if (path == "/"sv) {
97 return "@root";
98 }
99 if (path::isAbsolute(path)) {
100 path.remove_prefix(1);
101 }
102 std::string res(path);
103 std::replace(res.begin(), res.end(), '/', '_');
104 std::replace(res.begin(), res.end(), '@', '_');
105 return res;
106}
107
108static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
109 std::string_view path) {
110 auto mountKey = toMountKey(path);
111 const auto prefixSize = mountKey.size();
112 for (int counter = 0; counter < 1000;
113 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
114 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800115 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800116 return {mountKey, mountRoot};
117 }
118 }
119 return {};
120}
121
122template <class ProtoMessage, class Control>
123static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, Control&& control,
124 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800125 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800126 ProtoMessage message;
127 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
128}
129
130static bool isValidMountTarget(std::string_view path) {
131 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
132}
133
134std::string makeBindMdName() {
135 static constexpr auto uuidStringSize = 36;
136
137 uuid_t guid;
138 uuid_generate(guid);
139
140 std::string name;
141 const auto prefixSize = constants().mountpointMdPrefix.size();
142 name.reserve(prefixSize + uuidStringSize);
143
144 name = constants().mountpointMdPrefix;
145 name.resize(prefixSize + uuidStringSize);
146 uuid_unparse(guid, name.data() + prefixSize);
147
148 return name;
149}
150} // namespace
151
152IncrementalService::IncFsMount::~IncFsMount() {
153 incrementalService.mIncrementalManager->destroyDataLoader(mountId);
154 control.reset();
155 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
156 for (auto&& [target, _] : bindPoints) {
157 LOG(INFO) << "\tbind: " << target;
158 incrementalService.mVold->unmountIncFs(target);
159 }
160 LOG(INFO) << "\troot: " << root;
161 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
162 cleanupFilesystem(root);
163}
164
165auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800166 std::string name;
167 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
168 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
169 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800170 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
171 constants().storagePrefix.data(), id, no);
172 auto fullName = path::join(root, constants().mount, name);
Songchun Fan96100932020-02-03 19:20:58 -0800173 if (auto err = incrementalService.mIncFs->makeDir(control, fullName, 0755); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800174 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800175 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
176 } else if (err != EEXIST) {
177 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
178 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800179 }
180 }
181 nextStorageDirNo = 0;
182 return storages.end();
183}
184
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800185static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* path) {
186 return {::opendir(path), ::closedir};
187}
188
189static int rmDirContent(const char* path) {
190 auto dir = openDir(path);
191 if (!dir) {
192 return -EINVAL;
193 }
194 while (auto entry = ::readdir(dir.get())) {
195 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
196 continue;
197 }
198 auto fullPath = android::base::StringPrintf("%s/%s", path, entry->d_name);
199 if (entry->d_type == DT_DIR) {
200 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
201 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
202 return err;
203 }
204 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
205 PLOG(WARNING) << "Failed to rmdir " << fullPath;
206 return err;
207 }
208 } else {
209 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
210 PLOG(WARNING) << "Failed to delete " << fullPath;
211 return err;
212 }
213 }
214 }
215 return 0;
216}
217
Songchun Fan3c82a302019-11-29 14:23:45 -0800218void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800219 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800220 ::rmdir(path::join(root, constants().backing).c_str());
221 ::rmdir(path::join(root, constants().mount).c_str());
222 ::rmdir(path::c_str(root));
223}
224
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800225IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800226 : mVold(sm.getVoldService()),
227 mIncrementalManager(sm.getIncrementalManager()),
228 mIncFs(sm.getIncFs()),
229 mIncrementalDir(rootDir) {
230 if (!mVold) {
231 LOG(FATAL) << "Vold service is unavailable";
232 }
233 if (!mIncrementalManager) {
234 LOG(FATAL) << "IncrementalManager service is unavailable";
235 }
236 // TODO(b/136132412): check that root dir should already exist
237 // TODO(b/136132412): enable mount existing dirs after SELinux rules are merged
238 // mountExistingImages();
239}
240
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800241FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
242 incfs::FileId id = {};
243 if (size_t(metadata.size()) <= sizeof(id)) {
244 memcpy(&id, metadata.data(), metadata.size());
245 } else {
246 uint8_t buffer[SHA_DIGEST_LENGTH];
247 static_assert(sizeof(buffer) >= sizeof(id));
248
249 SHA_CTX ctx;
250 SHA1_Init(&ctx);
251 SHA1_Update(&ctx, metadata.data(), metadata.size());
252 SHA1_Final(buffer, &ctx);
253 memcpy(&id, buffer, sizeof(id));
254 }
255 return id;
256}
257
Songchun Fan3c82a302019-11-29 14:23:45 -0800258IncrementalService::~IncrementalService() = default;
259
Alex Buynytskyy18b07a42020-02-03 20:06:00 -0800260inline const char* toString(TimePoint t) {
261 using SystemClock = std::chrono::system_clock;
262 time_t time = SystemClock::to_time_t(SystemClock::now() + std::chrono::duration_cast<SystemClock::duration>(t - Clock::now()));
263 return std::ctime(&time);
264}
265
266inline const char* toString(IncrementalService::BindKind kind) {
267 switch (kind) {
268 case IncrementalService::BindKind::Temporary:
269 return "Temporary";
270 case IncrementalService::BindKind::Permanent:
271 return "Permanent";
272 }
273}
274
275void IncrementalService::onDump(int fd) {
276 dprintf(fd, "Incremental is %s\n", incfs::enabled() ? "ENABLED" : "DISABLED");
277 dprintf(fd, "Incremental dir: %s\n", mIncrementalDir.c_str());
278
279 std::unique_lock l(mLock);
280
281 dprintf(fd, "Mounts (%d):\n", int(mMounts.size()));
282 for (auto&& [id, ifs] : mMounts) {
283 const IncFsMount& mnt = *ifs.get();
284 dprintf(fd, "\t[%d]:\n", id);
285 dprintf(fd, "\t\tmountId: %d\n", mnt.mountId);
286 dprintf(fd, "\t\tnextStorageDirNo: %d\n", mnt.nextStorageDirNo.load());
287 dprintf(fd, "\t\tdataLoaderStatus: %d\n", mnt.dataLoaderStatus.load());
288 dprintf(fd, "\t\tconnectionLostTime: %s\n", toString(mnt.connectionLostTime));
289 if (mnt.savedDataLoaderParams) {
290 const auto& params = mnt.savedDataLoaderParams.value();
291 dprintf(fd, "\t\tsavedDataLoaderParams:\n");
292 dprintf(fd, "\t\t\ttype: %s\n", toString(params.type).c_str());
293 dprintf(fd, "\t\t\tpackageName: %s\n", params.packageName.c_str());
294 dprintf(fd, "\t\t\tclassName: %s\n", params.className.c_str());
295 dprintf(fd, "\t\t\targuments: %s\n", params.arguments.c_str());
296 dprintf(fd, "\t\t\tdynamicArgs: %d\n", int(params.dynamicArgs.size()));
297 }
298 dprintf(fd, "\t\tstorages (%d):\n", int(mnt.storages.size()));
299 for (auto&& [storageId, storage] : mnt.storages) {
300 dprintf(fd, "\t\t\t[%d] -> [%s]\n", storageId, storage.name.c_str());
301 }
302
303 dprintf(fd, "\t\tbindPoints (%d):\n", int(mnt.bindPoints.size()));
304 for (auto&& [target, bind] : mnt.bindPoints) {
305 dprintf(fd, "\t\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
306 dprintf(fd, "\t\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
307 dprintf(fd, "\t\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
308 dprintf(fd, "\t\t\t\tkind: %s\n", toString(bind.kind));
309 }
310 }
311
312 dprintf(fd, "Sorted binds (%d):\n", int(mBindsByPath.size()));
313 for (auto&& [target, mountPairIt] : mBindsByPath) {
314 const auto& bind = mountPairIt->second;
315 dprintf(fd, "\t\t[%s]->[%d]:\n", target.c_str(), bind.storage);
316 dprintf(fd, "\t\t\tsavedFilename: %s\n", bind.savedFilename.c_str());
317 dprintf(fd, "\t\t\tsourceDir: %s\n", bind.sourceDir.c_str());
318 dprintf(fd, "\t\t\tkind: %s\n", toString(bind.kind));
319 }
320}
321
Songchun Fan3c82a302019-11-29 14:23:45 -0800322std::optional<std::future<void>> IncrementalService::onSystemReady() {
323 std::promise<void> threadFinished;
324 if (mSystemReady.exchange(true)) {
325 return {};
326 }
327
328 std::vector<IfsMountPtr> mounts;
329 {
330 std::lock_guard l(mLock);
331 mounts.reserve(mMounts.size());
332 for (auto&& [id, ifs] : mMounts) {
333 if (ifs->mountId == id) {
334 mounts.push_back(ifs);
335 }
336 }
337 }
338
339 std::thread([this, mounts = std::move(mounts)]() {
340 std::vector<IfsMountPtr> failedLoaderMounts;
341 for (auto&& ifs : mounts) {
342 if (prepareDataLoader(*ifs, nullptr)) {
343 LOG(INFO) << "Successfully started data loader for mount " << ifs->mountId;
344 } else {
345 LOG(WARNING) << "Failed to start data loader for mount " << ifs->mountId;
346 failedLoaderMounts.push_back(std::move(ifs));
347 }
348 }
349
350 while (!failedLoaderMounts.empty()) {
351 LOG(WARNING) << "Deleting failed mount " << failedLoaderMounts.back()->mountId;
352 deleteStorage(*failedLoaderMounts.back());
353 failedLoaderMounts.pop_back();
354 }
355 mPrepareDataLoaders.set_value_at_thread_exit();
356 }).detach();
357 return mPrepareDataLoaders.get_future();
358}
359
360auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
361 for (;;) {
362 if (mNextId == kMaxStorageId) {
363 mNextId = 0;
364 }
365 auto id = ++mNextId;
366 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
367 if (inserted) {
368 return it;
369 }
370 }
371}
372
373StorageId IncrementalService::createStorage(std::string_view mountPoint,
374 DataLoaderParamsParcel&& dataLoaderParams,
375 CreateOptions options) {
376 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
377 if (!path::isAbsolute(mountPoint)) {
378 LOG(ERROR) << "path is not absolute: " << mountPoint;
379 return kInvalidStorageId;
380 }
381
382 auto mountNorm = path::normalize(mountPoint);
383 {
384 const auto id = findStorageId(mountNorm);
385 if (id != kInvalidStorageId) {
386 if (options & CreateOptions::OpenExisting) {
387 LOG(INFO) << "Opened existing storage " << id;
388 return id;
389 }
390 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
391 return kInvalidStorageId;
392 }
393 }
394
395 if (!(options & CreateOptions::CreateNew)) {
396 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
397 return kInvalidStorageId;
398 }
399
400 if (!path::isEmptyDir(mountNorm)) {
401 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
402 return kInvalidStorageId;
403 }
404 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
405 if (mountRoot.empty()) {
406 LOG(ERROR) << "Bad mount point";
407 return kInvalidStorageId;
408 }
409 // Make sure the code removes all crap it may create while still failing.
410 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
411 auto firstCleanupOnFailure =
412 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
413
414 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800415 const auto backing = path::join(mountRoot, constants().backing);
416 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800417 return kInvalidStorageId;
418 }
419
Songchun Fan3c82a302019-11-29 14:23:45 -0800420 IncFsMount::Control control;
421 {
422 std::lock_guard l(mMountOperationLock);
423 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800424
425 if (auto err = rmDirContent(backing.c_str())) {
426 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
427 return kInvalidStorageId;
428 }
429 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
430 return kInvalidStorageId;
431 }
432 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800433 if (!status.isOk()) {
434 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
435 return kInvalidStorageId;
436 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800437 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
438 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800439 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
440 return kInvalidStorageId;
441 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800442 control.cmd = controlParcel.cmd.release().release();
443 control.pendingReads = controlParcel.pendingReads.release().release();
444 control.logs = controlParcel.log.release().release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800445 }
446
447 std::unique_lock l(mLock);
448 const auto mountIt = getStorageSlotLocked();
449 const auto mountId = mountIt->first;
450 l.unlock();
451
452 auto ifs =
453 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
454 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
455 // is the removal of the |ifs|.
456 firstCleanupOnFailure.release();
457
458 auto secondCleanup = [this, &l](auto itPtr) {
459 if (!l.owns_lock()) {
460 l.lock();
461 }
462 mMounts.erase(*itPtr);
463 };
464 auto secondCleanupOnFailure =
465 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
466
467 const auto storageIt = ifs->makeStorage(ifs->mountId);
468 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800469 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800470 return kInvalidStorageId;
471 }
472
473 {
474 metadata::Mount m;
475 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800476 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Songchun Fan3c82a302019-11-29 14:23:45 -0800477 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800478 m.mutable_loader()->set_class_name(dataLoaderParams.className);
479 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800480 const auto metadata = m.SerializeAsString();
481 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800482 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800483 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800484 if (auto err =
485 mIncFs->makeFile(ifs->control,
486 path::join(ifs->root, constants().mount,
487 constants().infoMdName),
488 0777, idFromMetadata(metadata),
489 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800490 LOG(ERROR) << "Saving mount metadata failed: " << -err;
491 return kInvalidStorageId;
492 }
493 }
494
495 const auto bk =
496 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800497 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
498 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800499 err < 0) {
500 LOG(ERROR) << "adding bind mount failed: " << -err;
501 return kInvalidStorageId;
502 }
503
504 // Done here as well, all data structures are in good state.
505 secondCleanupOnFailure.release();
506
507 if (!prepareDataLoader(*ifs, &dataLoaderParams)) {
508 LOG(ERROR) << "prepareDataLoader() failed";
509 deleteStorageLocked(*ifs, std::move(l));
510 return kInvalidStorageId;
511 }
512
513 mountIt->second = std::move(ifs);
514 l.unlock();
515 LOG(INFO) << "created storage " << mountId;
516 return mountId;
517}
518
519StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
520 StorageId linkedStorage,
521 IncrementalService::CreateOptions options) {
522 if (!isValidMountTarget(mountPoint)) {
523 LOG(ERROR) << "Mount point is invalid or missing";
524 return kInvalidStorageId;
525 }
526
527 std::unique_lock l(mLock);
528 const auto& ifs = getIfsLocked(linkedStorage);
529 if (!ifs) {
530 LOG(ERROR) << "Ifs unavailable";
531 return kInvalidStorageId;
532 }
533
534 const auto mountIt = getStorageSlotLocked();
535 const auto storageId = mountIt->first;
536 const auto storageIt = ifs->makeStorage(storageId);
537 if (storageIt == ifs->storages.end()) {
538 LOG(ERROR) << "Can't create a new storage";
539 mMounts.erase(mountIt);
540 return kInvalidStorageId;
541 }
542
543 l.unlock();
544
545 const auto bk =
546 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800547 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
548 std::string(storageIt->second.name), path::normalize(mountPoint),
549 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800550 err < 0) {
551 LOG(ERROR) << "bindMount failed with error: " << err;
552 return kInvalidStorageId;
553 }
554
555 mountIt->second = ifs;
556 return storageId;
557}
558
559IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
560 std::string_view path) const {
561 auto bindPointIt = mBindsByPath.upper_bound(path);
562 if (bindPointIt == mBindsByPath.begin()) {
563 return mBindsByPath.end();
564 }
565 --bindPointIt;
566 if (!path::startsWith(path, bindPointIt->first)) {
567 return mBindsByPath.end();
568 }
569 return bindPointIt;
570}
571
572StorageId IncrementalService::findStorageId(std::string_view path) const {
573 std::lock_guard l(mLock);
574 auto it = findStorageLocked(path);
575 if (it == mBindsByPath.end()) {
576 return kInvalidStorageId;
577 }
578 return it->second->second.storage;
579}
580
581void IncrementalService::deleteStorage(StorageId storageId) {
582 const auto ifs = getIfs(storageId);
583 if (!ifs) {
584 return;
585 }
586 deleteStorage(*ifs);
587}
588
589void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
590 std::unique_lock l(ifs.lock);
591 deleteStorageLocked(ifs, std::move(l));
592}
593
594void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
595 std::unique_lock<std::mutex>&& ifsLock) {
596 const auto storages = std::move(ifs.storages);
597 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
598 const auto bindPoints = ifs.bindPoints;
599 ifsLock.unlock();
600
601 std::lock_guard l(mLock);
602 for (auto&& [id, _] : storages) {
603 if (id != ifs.mountId) {
604 mMounts.erase(id);
605 }
606 }
607 for (auto&& [path, _] : bindPoints) {
608 mBindsByPath.erase(path);
609 }
610 mMounts.erase(ifs.mountId);
611}
612
613StorageId IncrementalService::openStorage(std::string_view pathInMount) {
614 if (!path::isAbsolute(pathInMount)) {
615 return kInvalidStorageId;
616 }
617
618 return findStorageId(path::normalize(pathInMount));
619}
620
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800621FileId IncrementalService::nodeFor(StorageId storage, std::string_view subpath) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800622 const auto ifs = getIfs(storage);
623 if (!ifs) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800624 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800625 }
626 std::unique_lock l(ifs->lock);
627 auto storageIt = ifs->storages.find(storage);
628 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800629 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800630 }
631 if (subpath.empty() || subpath == "."sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800632 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800633 }
634 auto path = path::join(ifs->root, constants().mount, storageIt->second.name, subpath);
635 l.unlock();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800636 return mIncFs->getFileId(ifs->control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800637}
638
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800639std::pair<FileId, std::string_view> IncrementalService::parentAndNameFor(
Songchun Fan3c82a302019-11-29 14:23:45 -0800640 StorageId storage, std::string_view subpath) const {
641 auto name = path::basename(subpath);
642 if (name.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800643 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800644 }
645 auto dir = path::dirname(subpath);
646 if (dir.empty() || dir == "/"sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800647 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800648 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800649 auto id = nodeFor(storage, dir);
650 return {id, name};
Songchun Fan3c82a302019-11-29 14:23:45 -0800651}
652
653IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
654 std::lock_guard l(mLock);
655 return getIfsLocked(storage);
656}
657
658const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
659 auto it = mMounts.find(storage);
660 if (it == mMounts.end()) {
661 static const IfsMountPtr kEmpty = {};
662 return kEmpty;
663 }
664 return it->second;
665}
666
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800667int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
668 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800669 if (!isValidMountTarget(target)) {
670 return -EINVAL;
671 }
672
673 const auto ifs = getIfs(storage);
674 if (!ifs) {
675 return -EINVAL;
676 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800677
Songchun Fan3c82a302019-11-29 14:23:45 -0800678 std::unique_lock l(ifs->lock);
679 const auto storageInfo = ifs->storages.find(storage);
680 if (storageInfo == ifs->storages.end()) {
681 return -EINVAL;
682 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800683 std::string normSource = normalizePathToStorage(ifs, storage, source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800684 l.unlock();
685 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800686 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
687 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800688}
689
690int IncrementalService::unbind(StorageId storage, std::string_view target) {
691 if (!path::isAbsolute(target)) {
692 return -EINVAL;
693 }
694
695 LOG(INFO) << "Removing bind point " << target;
696
697 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
698 // otherwise there's a chance to unmount something completely unrelated
699 const auto norm = path::normalize(target);
700 std::unique_lock l(mLock);
701 const auto storageIt = mBindsByPath.find(norm);
702 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
703 return -EINVAL;
704 }
705 const auto bindIt = storageIt->second;
706 const auto storageId = bindIt->second.storage;
707 const auto ifs = getIfsLocked(storageId);
708 if (!ifs) {
709 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
710 << " is missing";
711 return -EFAULT;
712 }
713 mBindsByPath.erase(storageIt);
714 l.unlock();
715
716 mVold->unmountIncFs(bindIt->first);
717 std::unique_lock l2(ifs->lock);
718 if (ifs->bindPoints.size() <= 1) {
719 ifs->bindPoints.clear();
720 deleteStorageLocked(*ifs, std::move(l2));
721 } else {
722 const std::string savedFile = std::move(bindIt->second.savedFilename);
723 ifs->bindPoints.erase(bindIt);
724 l2.unlock();
725 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800726 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800727 }
728 }
729 return 0;
730}
731
Songchun Fan103ba1d2020-02-03 17:32:32 -0800732std::string IncrementalService::normalizePathToStorage(const IncrementalService::IfsMountPtr ifs,
733 StorageId storage, std::string_view path) {
734 const auto storageInfo = ifs->storages.find(storage);
735 if (storageInfo == ifs->storages.end()) {
736 return {};
737 }
738 std::string normPath;
739 if (path::isAbsolute(path)) {
740 normPath = path::normalize(path);
741 } else {
742 normPath = path::normalize(path::join(storageInfo->second.name, path));
743 }
744 if (!path::startsWith(normPath, storageInfo->second.name)) {
745 return {};
746 }
747 return normPath;
748}
749
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800750int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
751 incfs::NewFileParams params) {
752 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800753 std::string normPath = normalizePathToStorage(ifs, storage, path);
754 if (normPath.empty()) {
Songchun Fan54c6aed2020-01-31 16:52:41 -0800755 return -EINVAL;
756 }
757 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800758 if (err) {
759 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800760 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800761 std::vector<uint8_t> metadataBytes;
762 if (params.metadata.data && params.metadata.size > 0) {
763 metadataBytes.assign(params.metadata.data, params.metadata.data + params.metadata.size);
Songchun Fan3c82a302019-11-29 14:23:45 -0800764 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800765 mIncrementalManager->newFileForDataLoader(ifs->mountId, id, metadataBytes);
766 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800767 }
768 return -EINVAL;
769}
770
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800771int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800772 if (auto ifs = getIfs(storageId)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800773 std::string normPath = normalizePathToStorage(ifs, storageId, path);
774 if (normPath.empty()) {
775 return -EINVAL;
776 }
777 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800778 }
779 return -EINVAL;
780}
781
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800782int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800783 const auto ifs = getIfs(storageId);
784 if (!ifs) {
785 return -EINVAL;
786 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800787 std::string normPath = normalizePathToStorage(ifs, storageId, path);
788 if (normPath.empty()) {
789 return -EINVAL;
790 }
791 auto err = mIncFs->makeDir(ifs->control, normPath, mode);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800792 if (err == -EEXIST) {
793 return 0;
794 } else if (err != -ENOENT) {
795 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800796 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800797 if (auto err = makeDirs(storageId, path::dirname(normPath), mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800798 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800799 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800800 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800801}
802
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800803int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
804 StorageId destStorageId, std::string_view newPath) {
805 if (auto ifsSrc = getIfs(sourceStorageId), ifsDest = getIfs(destStorageId);
806 ifsSrc && ifsSrc == ifsDest) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800807 std::string normOldPath = normalizePathToStorage(ifsSrc, sourceStorageId, oldPath);
808 std::string normNewPath = normalizePathToStorage(ifsDest, destStorageId, newPath);
809 if (normOldPath.empty() || normNewPath.empty()) {
810 return -EINVAL;
811 }
812 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800813 }
814 return -EINVAL;
815}
816
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800817int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800818 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800819 std::string normOldPath = normalizePathToStorage(ifs, storage, path);
820 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800821 }
822 return -EINVAL;
823}
824
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800825int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
826 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800827 std::string&& target, BindKind kind,
828 std::unique_lock<std::mutex>& mainLock) {
829 if (!isValidMountTarget(target)) {
830 return -EINVAL;
831 }
832
833 std::string mdFileName;
834 if (kind != BindKind::Temporary) {
835 metadata::BindPoint bp;
836 bp.set_storage_id(storage);
837 bp.set_allocated_dest_path(&target);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800838 bp.set_source_subdir(std::string(path::relativize(storageRoot, source)));
Songchun Fan3c82a302019-11-29 14:23:45 -0800839 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800840 bp.release_dest_path();
841 mdFileName = makeBindMdName();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800842 auto node =
843 mIncFs->makeFile(ifs.control, path::join(ifs.root, constants().mount, mdFileName),
844 0444, idFromMetadata(metadata),
845 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
846 if (node) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800847 return int(node);
848 }
849 }
850
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800851 return addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
Songchun Fan3c82a302019-11-29 14:23:45 -0800852 std::move(target), kind, mainLock);
853}
854
855int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800856 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800857 std::string&& target, BindKind kind,
858 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800859 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800860 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800861 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800862 if (!status.isOk()) {
863 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
864 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
865 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
866 : status.serviceSpecificErrorCode() == 0
867 ? -EFAULT
868 : status.serviceSpecificErrorCode()
869 : -EIO;
870 }
871 }
872
873 if (!mainLock.owns_lock()) {
874 mainLock.lock();
875 }
876 std::lock_guard l(ifs.lock);
877 const auto [it, _] =
878 ifs.bindPoints.insert_or_assign(target,
879 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800880 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800881 mBindsByPath[std::move(target)] = it;
882 return 0;
883}
884
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800885RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800886 const auto ifs = getIfs(storage);
887 if (!ifs) {
888 return {};
889 }
890 return mIncFs->getMetadata(ifs->control, node);
891}
892
893std::vector<std::string> IncrementalService::listFiles(StorageId storage) const {
894 const auto ifs = getIfs(storage);
895 if (!ifs) {
896 return {};
897 }
898
899 std::unique_lock l(ifs->lock);
900 auto subdirIt = ifs->storages.find(storage);
901 if (subdirIt == ifs->storages.end()) {
902 return {};
903 }
904 auto dir = path::join(ifs->root, constants().mount, subdirIt->second.name);
905 l.unlock();
906
907 const auto prefixSize = dir.size() + 1;
908 std::vector<std::string> todoDirs{std::move(dir)};
909 std::vector<std::string> result;
910 do {
911 auto currDir = std::move(todoDirs.back());
912 todoDirs.pop_back();
913
914 auto d =
915 std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(currDir.c_str()), ::closedir);
916 while (auto e = ::readdir(d.get())) {
917 if (e->d_type == DT_REG) {
918 result.emplace_back(
919 path::join(std::string_view(currDir).substr(prefixSize), e->d_name));
920 continue;
921 }
922 if (e->d_type == DT_DIR) {
923 if (e->d_name == "."sv || e->d_name == ".."sv) {
924 continue;
925 }
926 todoDirs.emplace_back(path::join(currDir, e->d_name));
927 continue;
928 }
929 }
930 } while (!todoDirs.empty());
931 return result;
932}
933
934bool IncrementalService::startLoading(StorageId storage) const {
935 const auto ifs = getIfs(storage);
936 if (!ifs) {
937 return false;
938 }
939 bool started = false;
940 std::unique_lock l(ifs->lock);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800941 if (ifs->dataLoaderStatus != IDataLoaderStatusListener::DATA_LOADER_CREATED) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800942 if (ifs->dataLoaderReady.wait_for(l, Seconds(5)) == std::cv_status::timeout) {
943 LOG(ERROR) << "Timeout waiting for data loader to be ready";
944 return false;
945 }
946 }
947 auto status = mIncrementalManager->startDataLoader(ifs->mountId, &started);
948 if (!status.isOk()) {
949 return false;
950 }
951 return started;
952}
953
954void IncrementalService::mountExistingImages() {
955 auto d = std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(mIncrementalDir.c_str()),
956 ::closedir);
957 while (auto e = ::readdir(d.get())) {
958 if (e->d_type != DT_DIR) {
959 continue;
960 }
961 if (e->d_name == "."sv || e->d_name == ".."sv) {
962 continue;
963 }
964 auto root = path::join(mIncrementalDir, e->d_name);
965 if (!mountExistingImage(root, e->d_name)) {
966 IncFsMount::cleanupFilesystem(root);
967 }
968 }
969}
970
971bool IncrementalService::mountExistingImage(std::string_view root, std::string_view key) {
972 LOG(INFO) << "Trying to mount: " << key;
973
974 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800975 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -0800976
977 IncFsMount::Control control;
978 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800979 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800980 if (!status.isOk()) {
981 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
982 return false;
983 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800984 control.cmd = controlParcel.cmd.release().release();
985 control.pendingReads = controlParcel.pendingReads.release().release();
986 control.logs = controlParcel.log.release().release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800987
988 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
989
990 auto m = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
991 path::join(mountTarget, constants().infoMdName));
992 if (!m.has_loader() || !m.has_storage()) {
993 LOG(ERROR) << "Bad mount metadata in mount at " << root;
994 return false;
995 }
996
997 ifs->mountId = m.storage().id();
998 mNextId = std::max(mNextId, ifs->mountId + 1);
999
1000 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001001 auto d = openDir(path::c_str(mountTarget));
Songchun Fan3c82a302019-11-29 14:23:45 -08001002 while (auto e = ::readdir(d.get())) {
1003 if (e->d_type == DT_REG) {
1004 auto name = std::string_view(e->d_name);
1005 if (name.starts_with(constants().mountpointMdPrefix)) {
1006 bindPoints.emplace_back(name,
1007 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
1008 ifs->control,
1009 path::join(mountTarget,
1010 name)));
1011 if (bindPoints.back().second.dest_path().empty() ||
1012 bindPoints.back().second.source_subdir().empty()) {
1013 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001014 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -08001015 }
1016 }
1017 } else if (e->d_type == DT_DIR) {
1018 if (e->d_name == "."sv || e->d_name == ".."sv) {
1019 continue;
1020 }
1021 auto name = std::string_view(e->d_name);
1022 if (name.starts_with(constants().storagePrefix)) {
1023 auto md = parseFromIncfs<metadata::Storage>(mIncFs.get(), ifs->control,
1024 path::join(mountTarget, name));
1025 auto [_, inserted] = mMounts.try_emplace(md.id(), ifs);
1026 if (!inserted) {
1027 LOG(WARNING) << "Ignoring storage with duplicate id " << md.id()
1028 << " for mount " << root;
1029 continue;
1030 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001031 ifs->storages.insert_or_assign(md.id(), IncFsMount::Storage{std::string(name)});
Songchun Fan3c82a302019-11-29 14:23:45 -08001032 mNextId = std::max(mNextId, md.id() + 1);
1033 }
1034 }
1035 }
1036
1037 if (ifs->storages.empty()) {
1038 LOG(WARNING) << "No valid storages in mount " << root;
1039 return false;
1040 }
1041
1042 int bindCount = 0;
1043 for (auto&& bp : bindPoints) {
1044 std::unique_lock l(mLock, std::defer_lock);
1045 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
1046 std::move(*bp.second.mutable_source_subdir()),
1047 std::move(*bp.second.mutable_dest_path()),
1048 BindKind::Permanent, l);
1049 }
1050
1051 if (bindCount == 0) {
1052 LOG(WARNING) << "No valid bind points for mount " << root;
1053 deleteStorage(*ifs);
1054 return false;
1055 }
1056
1057 DataLoaderParamsParcel dlParams;
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001058 dlParams.type = (DataLoaderType)m.loader().type();
Songchun Fan3c82a302019-11-29 14:23:45 -08001059 dlParams.packageName = std::move(*m.mutable_loader()->mutable_package_name());
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001060 dlParams.className = std::move(*m.mutable_loader()->mutable_class_name());
1061 dlParams.arguments = std::move(*m.mutable_loader()->mutable_arguments());
Songchun Fan3c82a302019-11-29 14:23:45 -08001062 if (!prepareDataLoader(*ifs, &dlParams)) {
1063 deleteStorage(*ifs);
1064 return false;
1065 }
1066
1067 mMounts[ifs->mountId] = std::move(ifs);
1068 return true;
1069}
1070
1071bool IncrementalService::prepareDataLoader(IncrementalService::IncFsMount& ifs,
1072 DataLoaderParamsParcel* params) {
1073 if (!mSystemReady.load(std::memory_order_relaxed)) {
1074 std::unique_lock l(ifs.lock);
1075 if (params) {
1076 if (ifs.savedDataLoaderParams) {
1077 LOG(WARNING) << "Trying to pass second set of data loader parameters, ignored it";
1078 } else {
1079 ifs.savedDataLoaderParams = std::move(*params);
1080 }
1081 } else {
1082 if (!ifs.savedDataLoaderParams) {
1083 LOG(ERROR) << "Mount " << ifs.mountId
1084 << " is broken: no data loader params (system is not ready yet)";
1085 return false;
1086 }
1087 }
1088 return true; // eventually...
1089 }
1090 if (base::GetBoolProperty("incremental.skip_loader", false)) {
1091 LOG(INFO) << "Skipped data loader because of incremental.skip_loader property";
1092 std::unique_lock l(ifs.lock);
1093 ifs.savedDataLoaderParams.reset();
1094 return true;
1095 }
1096
1097 std::unique_lock l(ifs.lock);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001098 if (ifs.dataLoaderStatus == IDataLoaderStatusListener::DATA_LOADER_CREATED) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001099 LOG(INFO) << "Skipped data loader preparation because it already exists";
1100 return true;
1101 }
1102
1103 auto* dlp = params ? params
1104 : ifs.savedDataLoaderParams ? &ifs.savedDataLoaderParams.value() : nullptr;
1105 if (!dlp) {
1106 LOG(ERROR) << "Mount " << ifs.mountId << " is broken: no data loader params";
1107 return false;
1108 }
1109 FileSystemControlParcel fsControlParcel;
1110 fsControlParcel.incremental = std::make_unique<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001111 fsControlParcel.incremental->cmd.reset(base::unique_fd(::dup(ifs.control.cmd)));
1112 fsControlParcel.incremental->pendingReads.reset(
1113 base::unique_fd(::dup(ifs.control.pendingReads)));
1114 fsControlParcel.incremental->log.reset(base::unique_fd(::dup(ifs.control.logs)));
Songchun Fan3c82a302019-11-29 14:23:45 -08001115 sp<IncrementalDataLoaderListener> listener = new IncrementalDataLoaderListener(*this);
1116 bool created = false;
1117 auto status = mIncrementalManager->prepareDataLoader(ifs.mountId, fsControlParcel, *dlp,
1118 listener, &created);
1119 if (!status.isOk() || !created) {
1120 LOG(ERROR) << "Failed to create a data loader for mount " << ifs.mountId;
1121 return false;
1122 }
1123 ifs.savedDataLoaderParams.reset();
1124 return true;
1125}
1126
1127binder::Status IncrementalService::IncrementalDataLoaderListener::onStatusChanged(MountId mountId,
1128 int newStatus) {
1129 std::unique_lock l(incrementalService.mLock);
1130 const auto& ifs = incrementalService.getIfsLocked(mountId);
1131 if (!ifs) {
1132 LOG(WARNING) << "Received data loader status " << int(newStatus) << " for unknown mount "
1133 << mountId;
1134 return binder::Status::ok();
1135 }
1136 ifs->dataLoaderStatus = newStatus;
1137 switch (newStatus) {
1138 case IDataLoaderStatusListener::DATA_LOADER_NO_CONNECTION: {
1139 auto now = Clock::now();
1140 if (ifs->connectionLostTime.time_since_epoch().count() == 0) {
1141 ifs->connectionLostTime = now;
1142 break;
1143 }
1144 auto duration =
1145 std::chrono::duration_cast<Seconds>(now - ifs->connectionLostTime).count();
1146 if (duration >= 10) {
1147 incrementalService.mIncrementalManager->showHealthBlockedUI(mountId);
1148 }
1149 break;
1150 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001151 case IDataLoaderStatusListener::DATA_LOADER_CONNECTION_OK: {
1152 ifs->dataLoaderStatus = IDataLoaderStatusListener::DATA_LOADER_STARTED;
1153 break;
1154 }
1155 case IDataLoaderStatusListener::DATA_LOADER_CREATED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001156 ifs->dataLoaderReady.notify_one();
1157 break;
1158 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001159 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001160 ifs->dataLoaderStatus = IDataLoaderStatusListener::DATA_LOADER_STOPPED;
1161 incrementalService.deleteStorageLocked(*ifs, std::move(l));
1162 break;
1163 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001164 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001165 break;
1166 }
1167 case IDataLoaderStatusListener::DATA_LOADER_STOPPED: {
1168 break;
1169 }
1170 default: {
1171 LOG(WARNING) << "Unknown data loader status: " << newStatus
1172 << " for mount: " << mountId;
1173 break;
1174 }
1175 }
1176
1177 return binder::Status::ok();
1178}
1179
1180} // namespace android::incremental