blob: ac45d7695ab9123051ff9215e01adbc3d6adee67 [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
38#include <iterator>
39#include <span>
40#include <stack>
41#include <thread>
42#include <type_traits>
43
44#include "Metadata.pb.h"
45
46using namespace std::literals;
47using namespace android::content::pm;
48
49namespace android::incremental {
50
51namespace {
52
53using IncrementalFileSystemControlParcel =
54 ::android::os::incremental::IncrementalFileSystemControlParcel;
55
56struct Constants {
57 static constexpr auto backing = "backing_store"sv;
58 static constexpr auto mount = "mount"sv;
Songchun Fan3c82a302019-11-29 14:23:45 -080059 static constexpr auto storagePrefix = "st"sv;
60 static constexpr auto mountpointMdPrefix = ".mountpoint."sv;
61 static constexpr auto infoMdName = ".info"sv;
62};
63
64static const Constants& constants() {
65 static Constants c;
66 return c;
67}
68
69template <base::LogSeverity level = base::ERROR>
70bool mkdirOrLog(std::string_view name, int mode = 0770, bool allowExisting = true) {
71 auto cstr = path::c_str(name);
72 if (::mkdir(cstr, mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080073 if (!allowExisting || errno != EEXIST) {
Songchun Fan3c82a302019-11-29 14:23:45 -080074 PLOG(level) << "Can't create directory '" << name << '\'';
75 return false;
76 }
77 struct stat st;
78 if (::stat(cstr, &st) || !S_ISDIR(st.st_mode)) {
79 PLOG(level) << "Path exists but is not a directory: '" << name << '\'';
80 return false;
81 }
82 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -080083 if (::chmod(cstr, mode)) {
84 PLOG(level) << "Changing permission failed for '" << name << '\'';
85 return false;
86 }
87
Songchun Fan3c82a302019-11-29 14:23:45 -080088 return true;
89}
90
91static std::string toMountKey(std::string_view path) {
92 if (path.empty()) {
93 return "@none";
94 }
95 if (path == "/"sv) {
96 return "@root";
97 }
98 if (path::isAbsolute(path)) {
99 path.remove_prefix(1);
100 }
101 std::string res(path);
102 std::replace(res.begin(), res.end(), '/', '_');
103 std::replace(res.begin(), res.end(), '@', '_');
104 return res;
105}
106
107static std::pair<std::string, std::string> makeMountDir(std::string_view incrementalDir,
108 std::string_view path) {
109 auto mountKey = toMountKey(path);
110 const auto prefixSize = mountKey.size();
111 for (int counter = 0; counter < 1000;
112 mountKey.resize(prefixSize), base::StringAppendF(&mountKey, "%d", counter++)) {
113 auto mountRoot = path::join(incrementalDir, mountKey);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800114 if (mkdirOrLog(mountRoot, 0777, false)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800115 return {mountKey, mountRoot};
116 }
117 }
118 return {};
119}
120
121template <class ProtoMessage, class Control>
122static ProtoMessage parseFromIncfs(const IncFsWrapper* incfs, Control&& control,
123 std::string_view path) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800124 auto md = incfs->getMetadata(control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800125 ProtoMessage message;
126 return message.ParseFromArray(md.data(), md.size()) ? message : ProtoMessage{};
127}
128
129static bool isValidMountTarget(std::string_view path) {
130 return path::isAbsolute(path) && path::isEmptyDir(path).value_or(true);
131}
132
133std::string makeBindMdName() {
134 static constexpr auto uuidStringSize = 36;
135
136 uuid_t guid;
137 uuid_generate(guid);
138
139 std::string name;
140 const auto prefixSize = constants().mountpointMdPrefix.size();
141 name.reserve(prefixSize + uuidStringSize);
142
143 name = constants().mountpointMdPrefix;
144 name.resize(prefixSize + uuidStringSize);
145 uuid_unparse(guid, name.data() + prefixSize);
146
147 return name;
148}
149} // namespace
150
151IncrementalService::IncFsMount::~IncFsMount() {
152 incrementalService.mIncrementalManager->destroyDataLoader(mountId);
153 control.reset();
154 LOG(INFO) << "Unmounting and cleaning up mount " << mountId << " with root '" << root << '\'';
155 for (auto&& [target, _] : bindPoints) {
156 LOG(INFO) << "\tbind: " << target;
157 incrementalService.mVold->unmountIncFs(target);
158 }
159 LOG(INFO) << "\troot: " << root;
160 incrementalService.mVold->unmountIncFs(path::join(root, constants().mount));
161 cleanupFilesystem(root);
162}
163
164auto IncrementalService::IncFsMount::makeStorage(StorageId id) -> StorageMap::iterator {
Songchun Fan3c82a302019-11-29 14:23:45 -0800165 std::string name;
166 for (int no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), i = 0;
167 i < 1024 && no >= 0; no = nextStorageDirNo.fetch_add(1, std::memory_order_relaxed), ++i) {
168 name.clear();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800169 base::StringAppendF(&name, "%.*s_%d_%d", int(constants().storagePrefix.size()),
170 constants().storagePrefix.data(), id, no);
171 auto fullName = path::join(root, constants().mount, name);
172 if (auto err = incrementalService.mIncFs->makeDir(control, fullName); !err) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800173 std::lock_guard l(lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800174 return storages.insert_or_assign(id, Storage{std::move(fullName)}).first;
175 } else if (err != EEXIST) {
176 LOG(ERROR) << __func__ << "(): failed to create dir |" << fullName << "| " << err;
177 break;
Songchun Fan3c82a302019-11-29 14:23:45 -0800178 }
179 }
180 nextStorageDirNo = 0;
181 return storages.end();
182}
183
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800184static std::unique_ptr<DIR, decltype(&::closedir)> openDir(const char* path) {
185 return {::opendir(path), ::closedir};
186}
187
188static int rmDirContent(const char* path) {
189 auto dir = openDir(path);
190 if (!dir) {
191 return -EINVAL;
192 }
193 while (auto entry = ::readdir(dir.get())) {
194 if (entry->d_name == "."sv || entry->d_name == ".."sv) {
195 continue;
196 }
197 auto fullPath = android::base::StringPrintf("%s/%s", path, entry->d_name);
198 if (entry->d_type == DT_DIR) {
199 if (const auto err = rmDirContent(fullPath.c_str()); err != 0) {
200 PLOG(WARNING) << "Failed to delete " << fullPath << " content";
201 return err;
202 }
203 if (const auto err = ::rmdir(fullPath.c_str()); err != 0) {
204 PLOG(WARNING) << "Failed to rmdir " << fullPath;
205 return err;
206 }
207 } else {
208 if (const auto err = ::unlink(fullPath.c_str()); err != 0) {
209 PLOG(WARNING) << "Failed to delete " << fullPath;
210 return err;
211 }
212 }
213 }
214 return 0;
215}
216
Songchun Fan3c82a302019-11-29 14:23:45 -0800217void IncrementalService::IncFsMount::cleanupFilesystem(std::string_view root) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800218 rmDirContent(path::join(root, constants().backing).c_str());
Songchun Fan3c82a302019-11-29 14:23:45 -0800219 ::rmdir(path::join(root, constants().backing).c_str());
220 ::rmdir(path::join(root, constants().mount).c_str());
221 ::rmdir(path::c_str(root));
222}
223
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800224IncrementalService::IncrementalService(ServiceManagerWrapper&& sm, std::string_view rootDir)
Songchun Fan3c82a302019-11-29 14:23:45 -0800225 : mVold(sm.getVoldService()),
226 mIncrementalManager(sm.getIncrementalManager()),
227 mIncFs(sm.getIncFs()),
228 mIncrementalDir(rootDir) {
229 if (!mVold) {
230 LOG(FATAL) << "Vold service is unavailable";
231 }
232 if (!mIncrementalManager) {
233 LOG(FATAL) << "IncrementalManager service is unavailable";
234 }
235 // TODO(b/136132412): check that root dir should already exist
236 // TODO(b/136132412): enable mount existing dirs after SELinux rules are merged
237 // mountExistingImages();
238}
239
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800240FileId IncrementalService::idFromMetadata(std::span<const uint8_t> metadata) {
241 incfs::FileId id = {};
242 if (size_t(metadata.size()) <= sizeof(id)) {
243 memcpy(&id, metadata.data(), metadata.size());
244 } else {
245 uint8_t buffer[SHA_DIGEST_LENGTH];
246 static_assert(sizeof(buffer) >= sizeof(id));
247
248 SHA_CTX ctx;
249 SHA1_Init(&ctx);
250 SHA1_Update(&ctx, metadata.data(), metadata.size());
251 SHA1_Final(buffer, &ctx);
252 memcpy(&id, buffer, sizeof(id));
253 }
254 return id;
255}
256
Songchun Fan3c82a302019-11-29 14:23:45 -0800257IncrementalService::~IncrementalService() = default;
258
259std::optional<std::future<void>> IncrementalService::onSystemReady() {
260 std::promise<void> threadFinished;
261 if (mSystemReady.exchange(true)) {
262 return {};
263 }
264
265 std::vector<IfsMountPtr> mounts;
266 {
267 std::lock_guard l(mLock);
268 mounts.reserve(mMounts.size());
269 for (auto&& [id, ifs] : mMounts) {
270 if (ifs->mountId == id) {
271 mounts.push_back(ifs);
272 }
273 }
274 }
275
276 std::thread([this, mounts = std::move(mounts)]() {
277 std::vector<IfsMountPtr> failedLoaderMounts;
278 for (auto&& ifs : mounts) {
279 if (prepareDataLoader(*ifs, nullptr)) {
280 LOG(INFO) << "Successfully started data loader for mount " << ifs->mountId;
281 } else {
282 LOG(WARNING) << "Failed to start data loader for mount " << ifs->mountId;
283 failedLoaderMounts.push_back(std::move(ifs));
284 }
285 }
286
287 while (!failedLoaderMounts.empty()) {
288 LOG(WARNING) << "Deleting failed mount " << failedLoaderMounts.back()->mountId;
289 deleteStorage(*failedLoaderMounts.back());
290 failedLoaderMounts.pop_back();
291 }
292 mPrepareDataLoaders.set_value_at_thread_exit();
293 }).detach();
294 return mPrepareDataLoaders.get_future();
295}
296
297auto IncrementalService::getStorageSlotLocked() -> MountMap::iterator {
298 for (;;) {
299 if (mNextId == kMaxStorageId) {
300 mNextId = 0;
301 }
302 auto id = ++mNextId;
303 auto [it, inserted] = mMounts.try_emplace(id, nullptr);
304 if (inserted) {
305 return it;
306 }
307 }
308}
309
310StorageId IncrementalService::createStorage(std::string_view mountPoint,
311 DataLoaderParamsParcel&& dataLoaderParams,
312 CreateOptions options) {
313 LOG(INFO) << "createStorage: " << mountPoint << " | " << int(options);
314 if (!path::isAbsolute(mountPoint)) {
315 LOG(ERROR) << "path is not absolute: " << mountPoint;
316 return kInvalidStorageId;
317 }
318
319 auto mountNorm = path::normalize(mountPoint);
320 {
321 const auto id = findStorageId(mountNorm);
322 if (id != kInvalidStorageId) {
323 if (options & CreateOptions::OpenExisting) {
324 LOG(INFO) << "Opened existing storage " << id;
325 return id;
326 }
327 LOG(ERROR) << "Directory " << mountPoint << " is already mounted at storage " << id;
328 return kInvalidStorageId;
329 }
330 }
331
332 if (!(options & CreateOptions::CreateNew)) {
333 LOG(ERROR) << "not requirested create new storage, and it doesn't exist: " << mountPoint;
334 return kInvalidStorageId;
335 }
336
337 if (!path::isEmptyDir(mountNorm)) {
338 LOG(ERROR) << "Mounting over existing non-empty directory is not supported: " << mountNorm;
339 return kInvalidStorageId;
340 }
341 auto [mountKey, mountRoot] = makeMountDir(mIncrementalDir, mountNorm);
342 if (mountRoot.empty()) {
343 LOG(ERROR) << "Bad mount point";
344 return kInvalidStorageId;
345 }
346 // Make sure the code removes all crap it may create while still failing.
347 auto firstCleanup = [](const std::string* ptr) { IncFsMount::cleanupFilesystem(*ptr); };
348 auto firstCleanupOnFailure =
349 std::unique_ptr<std::string, decltype(firstCleanup)>(&mountRoot, firstCleanup);
350
351 auto mountTarget = path::join(mountRoot, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800352 const auto backing = path::join(mountRoot, constants().backing);
353 if (!mkdirOrLog(backing, 0777) || !mkdirOrLog(mountTarget)) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800354 return kInvalidStorageId;
355 }
356
Songchun Fan3c82a302019-11-29 14:23:45 -0800357 IncFsMount::Control control;
358 {
359 std::lock_guard l(mMountOperationLock);
360 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800361
362 if (auto err = rmDirContent(backing.c_str())) {
363 LOG(ERROR) << "Coudn't clean the backing directory " << backing << ": " << err;
364 return kInvalidStorageId;
365 }
366 if (!mkdirOrLog(path::join(backing, ".index"), 0777)) {
367 return kInvalidStorageId;
368 }
369 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800370 if (!status.isOk()) {
371 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
372 return kInvalidStorageId;
373 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800374 if (controlParcel.cmd.get() < 0 || controlParcel.pendingReads.get() < 0 ||
375 controlParcel.log.get() < 0) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800376 LOG(ERROR) << "Vold::mountIncFs() returned invalid control parcel.";
377 return kInvalidStorageId;
378 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800379 control.cmd = controlParcel.cmd.release().release();
380 control.pendingReads = controlParcel.pendingReads.release().release();
381 control.logs = controlParcel.log.release().release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800382 }
383
384 std::unique_lock l(mLock);
385 const auto mountIt = getStorageSlotLocked();
386 const auto mountId = mountIt->first;
387 l.unlock();
388
389 auto ifs =
390 std::make_shared<IncFsMount>(std::move(mountRoot), mountId, std::move(control), *this);
391 // Now it's the |ifs|'s responsibility to clean up after itself, and the only cleanup we need
392 // is the removal of the |ifs|.
393 firstCleanupOnFailure.release();
394
395 auto secondCleanup = [this, &l](auto itPtr) {
396 if (!l.owns_lock()) {
397 l.lock();
398 }
399 mMounts.erase(*itPtr);
400 };
401 auto secondCleanupOnFailure =
402 std::unique_ptr<decltype(mountIt), decltype(secondCleanup)>(&mountIt, secondCleanup);
403
404 const auto storageIt = ifs->makeStorage(ifs->mountId);
405 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800406 LOG(ERROR) << "Can't create a default storage directory";
Songchun Fan3c82a302019-11-29 14:23:45 -0800407 return kInvalidStorageId;
408 }
409
410 {
411 metadata::Mount m;
412 m.mutable_storage()->set_id(ifs->mountId);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800413 m.mutable_loader()->set_type((int)dataLoaderParams.type);
Songchun Fan3c82a302019-11-29 14:23:45 -0800414 m.mutable_loader()->set_package_name(dataLoaderParams.packageName);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800415 m.mutable_loader()->set_class_name(dataLoaderParams.className);
416 m.mutable_loader()->set_arguments(dataLoaderParams.arguments);
Songchun Fan3c82a302019-11-29 14:23:45 -0800417 const auto metadata = m.SerializeAsString();
418 m.mutable_loader()->release_arguments();
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800419 m.mutable_loader()->release_class_name();
Songchun Fan3c82a302019-11-29 14:23:45 -0800420 m.mutable_loader()->release_package_name();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800421 if (auto err =
422 mIncFs->makeFile(ifs->control,
423 path::join(ifs->root, constants().mount,
424 constants().infoMdName),
425 0777, idFromMetadata(metadata),
426 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}})) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800427 LOG(ERROR) << "Saving mount metadata failed: " << -err;
428 return kInvalidStorageId;
429 }
430 }
431
432 const auto bk =
433 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800434 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
435 std::string(storageIt->second.name), std::move(mountNorm), bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800436 err < 0) {
437 LOG(ERROR) << "adding bind mount failed: " << -err;
438 return kInvalidStorageId;
439 }
440
441 // Done here as well, all data structures are in good state.
442 secondCleanupOnFailure.release();
443
444 if (!prepareDataLoader(*ifs, &dataLoaderParams)) {
445 LOG(ERROR) << "prepareDataLoader() failed";
446 deleteStorageLocked(*ifs, std::move(l));
447 return kInvalidStorageId;
448 }
449
450 mountIt->second = std::move(ifs);
451 l.unlock();
452 LOG(INFO) << "created storage " << mountId;
453 return mountId;
454}
455
456StorageId IncrementalService::createLinkedStorage(std::string_view mountPoint,
457 StorageId linkedStorage,
458 IncrementalService::CreateOptions options) {
459 if (!isValidMountTarget(mountPoint)) {
460 LOG(ERROR) << "Mount point is invalid or missing";
461 return kInvalidStorageId;
462 }
463
464 std::unique_lock l(mLock);
465 const auto& ifs = getIfsLocked(linkedStorage);
466 if (!ifs) {
467 LOG(ERROR) << "Ifs unavailable";
468 return kInvalidStorageId;
469 }
470
471 const auto mountIt = getStorageSlotLocked();
472 const auto storageId = mountIt->first;
473 const auto storageIt = ifs->makeStorage(storageId);
474 if (storageIt == ifs->storages.end()) {
475 LOG(ERROR) << "Can't create a new storage";
476 mMounts.erase(mountIt);
477 return kInvalidStorageId;
478 }
479
480 l.unlock();
481
482 const auto bk =
483 (options & CreateOptions::PermanentBind) ? BindKind::Permanent : BindKind::Temporary;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800484 if (auto err = addBindMount(*ifs, storageIt->first, storageIt->second.name,
485 std::string(storageIt->second.name), path::normalize(mountPoint),
486 bk, l);
Songchun Fan3c82a302019-11-29 14:23:45 -0800487 err < 0) {
488 LOG(ERROR) << "bindMount failed with error: " << err;
489 return kInvalidStorageId;
490 }
491
492 mountIt->second = ifs;
493 return storageId;
494}
495
496IncrementalService::BindPathMap::const_iterator IncrementalService::findStorageLocked(
497 std::string_view path) const {
498 auto bindPointIt = mBindsByPath.upper_bound(path);
499 if (bindPointIt == mBindsByPath.begin()) {
500 return mBindsByPath.end();
501 }
502 --bindPointIt;
503 if (!path::startsWith(path, bindPointIt->first)) {
504 return mBindsByPath.end();
505 }
506 return bindPointIt;
507}
508
509StorageId IncrementalService::findStorageId(std::string_view path) const {
510 std::lock_guard l(mLock);
511 auto it = findStorageLocked(path);
512 if (it == mBindsByPath.end()) {
513 return kInvalidStorageId;
514 }
515 return it->second->second.storage;
516}
517
518void IncrementalService::deleteStorage(StorageId storageId) {
519 const auto ifs = getIfs(storageId);
520 if (!ifs) {
521 return;
522 }
523 deleteStorage(*ifs);
524}
525
526void IncrementalService::deleteStorage(IncrementalService::IncFsMount& ifs) {
527 std::unique_lock l(ifs.lock);
528 deleteStorageLocked(ifs, std::move(l));
529}
530
531void IncrementalService::deleteStorageLocked(IncrementalService::IncFsMount& ifs,
532 std::unique_lock<std::mutex>&& ifsLock) {
533 const auto storages = std::move(ifs.storages);
534 // Don't move the bind points out: Ifs's dtor will use them to unmount everything.
535 const auto bindPoints = ifs.bindPoints;
536 ifsLock.unlock();
537
538 std::lock_guard l(mLock);
539 for (auto&& [id, _] : storages) {
540 if (id != ifs.mountId) {
541 mMounts.erase(id);
542 }
543 }
544 for (auto&& [path, _] : bindPoints) {
545 mBindsByPath.erase(path);
546 }
547 mMounts.erase(ifs.mountId);
548}
549
550StorageId IncrementalService::openStorage(std::string_view pathInMount) {
551 if (!path::isAbsolute(pathInMount)) {
552 return kInvalidStorageId;
553 }
554
555 return findStorageId(path::normalize(pathInMount));
556}
557
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800558FileId IncrementalService::nodeFor(StorageId storage, std::string_view subpath) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800559 const auto ifs = getIfs(storage);
560 if (!ifs) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800561 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800562 }
563 std::unique_lock l(ifs->lock);
564 auto storageIt = ifs->storages.find(storage);
565 if (storageIt == ifs->storages.end()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800566 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800567 }
568 if (subpath.empty() || subpath == "."sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800569 return kIncFsInvalidFileId;
Songchun Fan3c82a302019-11-29 14:23:45 -0800570 }
571 auto path = path::join(ifs->root, constants().mount, storageIt->second.name, subpath);
572 l.unlock();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800573 return mIncFs->getFileId(ifs->control, path);
Songchun Fan3c82a302019-11-29 14:23:45 -0800574}
575
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800576std::pair<FileId, std::string_view> IncrementalService::parentAndNameFor(
Songchun Fan3c82a302019-11-29 14:23:45 -0800577 StorageId storage, std::string_view subpath) const {
578 auto name = path::basename(subpath);
579 if (name.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800580 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800581 }
582 auto dir = path::dirname(subpath);
583 if (dir.empty() || dir == "/"sv) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800584 return {kIncFsInvalidFileId, {}};
Songchun Fan3c82a302019-11-29 14:23:45 -0800585 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800586 auto id = nodeFor(storage, dir);
587 return {id, name};
Songchun Fan3c82a302019-11-29 14:23:45 -0800588}
589
590IncrementalService::IfsMountPtr IncrementalService::getIfs(StorageId storage) const {
591 std::lock_guard l(mLock);
592 return getIfsLocked(storage);
593}
594
595const IncrementalService::IfsMountPtr& IncrementalService::getIfsLocked(StorageId storage) const {
596 auto it = mMounts.find(storage);
597 if (it == mMounts.end()) {
598 static const IfsMountPtr kEmpty = {};
599 return kEmpty;
600 }
601 return it->second;
602}
603
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800604int IncrementalService::bind(StorageId storage, std::string_view source, std::string_view target,
605 BindKind kind) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800606 if (!isValidMountTarget(target)) {
607 return -EINVAL;
608 }
609
610 const auto ifs = getIfs(storage);
611 if (!ifs) {
612 return -EINVAL;
613 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800614
Songchun Fan3c82a302019-11-29 14:23:45 -0800615 std::unique_lock l(ifs->lock);
616 const auto storageInfo = ifs->storages.find(storage);
617 if (storageInfo == ifs->storages.end()) {
618 return -EINVAL;
619 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800620 std::string normSource = normalizePathToStorage(ifs, storage, source);
Songchun Fan3c82a302019-11-29 14:23:45 -0800621 l.unlock();
622 std::unique_lock l2(mLock, std::defer_lock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800623 return addBindMount(*ifs, storage, storageInfo->second.name, std::move(normSource),
624 path::normalize(target), kind, l2);
Songchun Fan3c82a302019-11-29 14:23:45 -0800625}
626
627int IncrementalService::unbind(StorageId storage, std::string_view target) {
628 if (!path::isAbsolute(target)) {
629 return -EINVAL;
630 }
631
632 LOG(INFO) << "Removing bind point " << target;
633
634 // Here we should only look up by the exact target, not by a subdirectory of any existing mount,
635 // otherwise there's a chance to unmount something completely unrelated
636 const auto norm = path::normalize(target);
637 std::unique_lock l(mLock);
638 const auto storageIt = mBindsByPath.find(norm);
639 if (storageIt == mBindsByPath.end() || storageIt->second->second.storage != storage) {
640 return -EINVAL;
641 }
642 const auto bindIt = storageIt->second;
643 const auto storageId = bindIt->second.storage;
644 const auto ifs = getIfsLocked(storageId);
645 if (!ifs) {
646 LOG(ERROR) << "Internal error: storageId " << storageId << " for bound path " << target
647 << " is missing";
648 return -EFAULT;
649 }
650 mBindsByPath.erase(storageIt);
651 l.unlock();
652
653 mVold->unmountIncFs(bindIt->first);
654 std::unique_lock l2(ifs->lock);
655 if (ifs->bindPoints.size() <= 1) {
656 ifs->bindPoints.clear();
657 deleteStorageLocked(*ifs, std::move(l2));
658 } else {
659 const std::string savedFile = std::move(bindIt->second.savedFilename);
660 ifs->bindPoints.erase(bindIt);
661 l2.unlock();
662 if (!savedFile.empty()) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800663 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, savedFile));
Songchun Fan3c82a302019-11-29 14:23:45 -0800664 }
665 }
666 return 0;
667}
668
Songchun Fan103ba1d2020-02-03 17:32:32 -0800669std::string IncrementalService::normalizePathToStorage(const IncrementalService::IfsMountPtr ifs,
670 StorageId storage, std::string_view path) {
671 const auto storageInfo = ifs->storages.find(storage);
672 if (storageInfo == ifs->storages.end()) {
673 return {};
674 }
675 std::string normPath;
676 if (path::isAbsolute(path)) {
677 normPath = path::normalize(path);
678 } else {
679 normPath = path::normalize(path::join(storageInfo->second.name, path));
680 }
681 if (!path::startsWith(normPath, storageInfo->second.name)) {
682 return {};
683 }
684 return normPath;
685}
686
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800687int IncrementalService::makeFile(StorageId storage, std::string_view path, int mode, FileId id,
688 incfs::NewFileParams params) {
689 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800690 std::string normPath = normalizePathToStorage(ifs, storage, path);
691 if (normPath.empty()) {
Songchun Fan54c6aed2020-01-31 16:52:41 -0800692 return -EINVAL;
693 }
694 auto err = mIncFs->makeFile(ifs->control, normPath, mode, id, params);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800695 if (err) {
696 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800697 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800698 std::vector<uint8_t> metadataBytes;
699 if (params.metadata.data && params.metadata.size > 0) {
700 metadataBytes.assign(params.metadata.data, params.metadata.data + params.metadata.size);
Songchun Fan3c82a302019-11-29 14:23:45 -0800701 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800702 mIncrementalManager->newFileForDataLoader(ifs->mountId, id, metadataBytes);
703 return 0;
Songchun Fan3c82a302019-11-29 14:23:45 -0800704 }
705 return -EINVAL;
706}
707
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800708int IncrementalService::makeDir(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800709 if (auto ifs = getIfs(storageId)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800710 std::string normPath = normalizePathToStorage(ifs, storageId, path);
711 if (normPath.empty()) {
712 return -EINVAL;
713 }
714 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800715 }
716 return -EINVAL;
717}
718
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800719int IncrementalService::makeDirs(StorageId storageId, std::string_view path, int mode) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800720 const auto ifs = getIfs(storageId);
721 if (!ifs) {
722 return -EINVAL;
723 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800724 std::string normPath = normalizePathToStorage(ifs, storageId, path);
725 if (normPath.empty()) {
726 return -EINVAL;
727 }
728 auto err = mIncFs->makeDir(ifs->control, normPath, mode);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800729 if (err == -EEXIST) {
730 return 0;
731 } else if (err != -ENOENT) {
732 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800733 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800734 if (auto err = makeDirs(storageId, path::dirname(normPath), mode)) {
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800735 return err;
Songchun Fan3c82a302019-11-29 14:23:45 -0800736 }
Songchun Fan103ba1d2020-02-03 17:32:32 -0800737 return mIncFs->makeDir(ifs->control, normPath, mode);
Songchun Fan3c82a302019-11-29 14:23:45 -0800738}
739
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800740int IncrementalService::link(StorageId sourceStorageId, std::string_view oldPath,
741 StorageId destStorageId, std::string_view newPath) {
742 if (auto ifsSrc = getIfs(sourceStorageId), ifsDest = getIfs(destStorageId);
743 ifsSrc && ifsSrc == ifsDest) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800744 std::string normOldPath = normalizePathToStorage(ifsSrc, sourceStorageId, oldPath);
745 std::string normNewPath = normalizePathToStorage(ifsDest, destStorageId, newPath);
746 if (normOldPath.empty() || normNewPath.empty()) {
747 return -EINVAL;
748 }
749 return mIncFs->link(ifsSrc->control, normOldPath, normNewPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800750 }
751 return -EINVAL;
752}
753
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800754int IncrementalService::unlink(StorageId storage, std::string_view path) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800755 if (auto ifs = getIfs(storage)) {
Songchun Fan103ba1d2020-02-03 17:32:32 -0800756 std::string normOldPath = normalizePathToStorage(ifs, storage, path);
757 return mIncFs->unlink(ifs->control, normOldPath);
Songchun Fan3c82a302019-11-29 14:23:45 -0800758 }
759 return -EINVAL;
760}
761
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800762int IncrementalService::addBindMount(IncFsMount& ifs, StorageId storage,
763 std::string_view storageRoot, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800764 std::string&& target, BindKind kind,
765 std::unique_lock<std::mutex>& mainLock) {
766 if (!isValidMountTarget(target)) {
767 return -EINVAL;
768 }
769
770 std::string mdFileName;
771 if (kind != BindKind::Temporary) {
772 metadata::BindPoint bp;
773 bp.set_storage_id(storage);
774 bp.set_allocated_dest_path(&target);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800775 bp.set_source_subdir(std::string(path::relativize(storageRoot, source)));
Songchun Fan3c82a302019-11-29 14:23:45 -0800776 const auto metadata = bp.SerializeAsString();
Songchun Fan3c82a302019-11-29 14:23:45 -0800777 bp.release_dest_path();
778 mdFileName = makeBindMdName();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800779 auto node =
780 mIncFs->makeFile(ifs.control, path::join(ifs.root, constants().mount, mdFileName),
781 0444, idFromMetadata(metadata),
782 {.metadata = {metadata.data(), (IncFsSize)metadata.size()}});
783 if (node) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800784 return int(node);
785 }
786 }
787
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800788 return addBindMountWithMd(ifs, storage, std::move(mdFileName), std::move(source),
Songchun Fan3c82a302019-11-29 14:23:45 -0800789 std::move(target), kind, mainLock);
790}
791
792int IncrementalService::addBindMountWithMd(IncrementalService::IncFsMount& ifs, StorageId storage,
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800793 std::string&& metadataName, std::string&& source,
Songchun Fan3c82a302019-11-29 14:23:45 -0800794 std::string&& target, BindKind kind,
795 std::unique_lock<std::mutex>& mainLock) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800796 {
Songchun Fan3c82a302019-11-29 14:23:45 -0800797 std::lock_guard l(mMountOperationLock);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800798 const auto status = mVold->bindMount(source, target);
Songchun Fan3c82a302019-11-29 14:23:45 -0800799 if (!status.isOk()) {
800 LOG(ERROR) << "Calling Vold::bindMount() failed: " << status.toString8();
801 return status.exceptionCode() == binder::Status::EX_SERVICE_SPECIFIC
802 ? status.serviceSpecificErrorCode() > 0 ? -status.serviceSpecificErrorCode()
803 : status.serviceSpecificErrorCode() == 0
804 ? -EFAULT
805 : status.serviceSpecificErrorCode()
806 : -EIO;
807 }
808 }
809
810 if (!mainLock.owns_lock()) {
811 mainLock.lock();
812 }
813 std::lock_guard l(ifs.lock);
814 const auto [it, _] =
815 ifs.bindPoints.insert_or_assign(target,
816 IncFsMount::Bind{storage, std::move(metadataName),
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800817 std::move(source), kind});
Songchun Fan3c82a302019-11-29 14:23:45 -0800818 mBindsByPath[std::move(target)] = it;
819 return 0;
820}
821
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800822RawMetadata IncrementalService::getMetadata(StorageId storage, FileId node) const {
Songchun Fan3c82a302019-11-29 14:23:45 -0800823 const auto ifs = getIfs(storage);
824 if (!ifs) {
825 return {};
826 }
827 return mIncFs->getMetadata(ifs->control, node);
828}
829
830std::vector<std::string> IncrementalService::listFiles(StorageId storage) const {
831 const auto ifs = getIfs(storage);
832 if (!ifs) {
833 return {};
834 }
835
836 std::unique_lock l(ifs->lock);
837 auto subdirIt = ifs->storages.find(storage);
838 if (subdirIt == ifs->storages.end()) {
839 return {};
840 }
841 auto dir = path::join(ifs->root, constants().mount, subdirIt->second.name);
842 l.unlock();
843
844 const auto prefixSize = dir.size() + 1;
845 std::vector<std::string> todoDirs{std::move(dir)};
846 std::vector<std::string> result;
847 do {
848 auto currDir = std::move(todoDirs.back());
849 todoDirs.pop_back();
850
851 auto d =
852 std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(currDir.c_str()), ::closedir);
853 while (auto e = ::readdir(d.get())) {
854 if (e->d_type == DT_REG) {
855 result.emplace_back(
856 path::join(std::string_view(currDir).substr(prefixSize), e->d_name));
857 continue;
858 }
859 if (e->d_type == DT_DIR) {
860 if (e->d_name == "."sv || e->d_name == ".."sv) {
861 continue;
862 }
863 todoDirs.emplace_back(path::join(currDir, e->d_name));
864 continue;
865 }
866 }
867 } while (!todoDirs.empty());
868 return result;
869}
870
871bool IncrementalService::startLoading(StorageId storage) const {
872 const auto ifs = getIfs(storage);
873 if (!ifs) {
874 return false;
875 }
876 bool started = false;
877 std::unique_lock l(ifs->lock);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800878 if (ifs->dataLoaderStatus != IDataLoaderStatusListener::DATA_LOADER_CREATED) {
Songchun Fan3c82a302019-11-29 14:23:45 -0800879 if (ifs->dataLoaderReady.wait_for(l, Seconds(5)) == std::cv_status::timeout) {
880 LOG(ERROR) << "Timeout waiting for data loader to be ready";
881 return false;
882 }
883 }
884 auto status = mIncrementalManager->startDataLoader(ifs->mountId, &started);
885 if (!status.isOk()) {
886 return false;
887 }
888 return started;
889}
890
891void IncrementalService::mountExistingImages() {
892 auto d = std::unique_ptr<DIR, decltype(&::closedir)>(::opendir(mIncrementalDir.c_str()),
893 ::closedir);
894 while (auto e = ::readdir(d.get())) {
895 if (e->d_type != DT_DIR) {
896 continue;
897 }
898 if (e->d_name == "."sv || e->d_name == ".."sv) {
899 continue;
900 }
901 auto root = path::join(mIncrementalDir, e->d_name);
902 if (!mountExistingImage(root, e->d_name)) {
903 IncFsMount::cleanupFilesystem(root);
904 }
905 }
906}
907
908bool IncrementalService::mountExistingImage(std::string_view root, std::string_view key) {
909 LOG(INFO) << "Trying to mount: " << key;
910
911 auto mountTarget = path::join(root, constants().mount);
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800912 const auto backing = path::join(root, constants().backing);
Songchun Fan3c82a302019-11-29 14:23:45 -0800913
914 IncFsMount::Control control;
915 IncrementalFileSystemControlParcel controlParcel;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800916 auto status = mVold->mountIncFs(backing, mountTarget, 0, &controlParcel);
Songchun Fan3c82a302019-11-29 14:23:45 -0800917 if (!status.isOk()) {
918 LOG(ERROR) << "Vold::mountIncFs() failed: " << status.toString8();
919 return false;
920 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800921 control.cmd = controlParcel.cmd.release().release();
922 control.pendingReads = controlParcel.pendingReads.release().release();
923 control.logs = controlParcel.log.release().release();
Songchun Fan3c82a302019-11-29 14:23:45 -0800924
925 auto ifs = std::make_shared<IncFsMount>(std::string(root), -1, std::move(control), *this);
926
927 auto m = parseFromIncfs<metadata::Mount>(mIncFs.get(), ifs->control,
928 path::join(mountTarget, constants().infoMdName));
929 if (!m.has_loader() || !m.has_storage()) {
930 LOG(ERROR) << "Bad mount metadata in mount at " << root;
931 return false;
932 }
933
934 ifs->mountId = m.storage().id();
935 mNextId = std::max(mNextId, ifs->mountId + 1);
936
937 std::vector<std::pair<std::string, metadata::BindPoint>> bindPoints;
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800938 auto d = openDir(path::c_str(mountTarget));
Songchun Fan3c82a302019-11-29 14:23:45 -0800939 while (auto e = ::readdir(d.get())) {
940 if (e->d_type == DT_REG) {
941 auto name = std::string_view(e->d_name);
942 if (name.starts_with(constants().mountpointMdPrefix)) {
943 bindPoints.emplace_back(name,
944 parseFromIncfs<metadata::BindPoint>(mIncFs.get(),
945 ifs->control,
946 path::join(mountTarget,
947 name)));
948 if (bindPoints.back().second.dest_path().empty() ||
949 bindPoints.back().second.source_subdir().empty()) {
950 bindPoints.pop_back();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800951 mIncFs->unlink(ifs->control, path::join(ifs->root, constants().mount, name));
Songchun Fan3c82a302019-11-29 14:23:45 -0800952 }
953 }
954 } else if (e->d_type == DT_DIR) {
955 if (e->d_name == "."sv || e->d_name == ".."sv) {
956 continue;
957 }
958 auto name = std::string_view(e->d_name);
959 if (name.starts_with(constants().storagePrefix)) {
960 auto md = parseFromIncfs<metadata::Storage>(mIncFs.get(), ifs->control,
961 path::join(mountTarget, name));
962 auto [_, inserted] = mMounts.try_emplace(md.id(), ifs);
963 if (!inserted) {
964 LOG(WARNING) << "Ignoring storage with duplicate id " << md.id()
965 << " for mount " << root;
966 continue;
967 }
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -0800968 ifs->storages.insert_or_assign(md.id(), IncFsMount::Storage{std::string(name)});
Songchun Fan3c82a302019-11-29 14:23:45 -0800969 mNextId = std::max(mNextId, md.id() + 1);
970 }
971 }
972 }
973
974 if (ifs->storages.empty()) {
975 LOG(WARNING) << "No valid storages in mount " << root;
976 return false;
977 }
978
979 int bindCount = 0;
980 for (auto&& bp : bindPoints) {
981 std::unique_lock l(mLock, std::defer_lock);
982 bindCount += !addBindMountWithMd(*ifs, bp.second.storage_id(), std::move(bp.first),
983 std::move(*bp.second.mutable_source_subdir()),
984 std::move(*bp.second.mutable_dest_path()),
985 BindKind::Permanent, l);
986 }
987
988 if (bindCount == 0) {
989 LOG(WARNING) << "No valid bind points for mount " << root;
990 deleteStorage(*ifs);
991 return false;
992 }
993
994 DataLoaderParamsParcel dlParams;
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800995 dlParams.type = (DataLoaderType)m.loader().type();
Songchun Fan3c82a302019-11-29 14:23:45 -0800996 dlParams.packageName = std::move(*m.mutable_loader()->mutable_package_name());
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -0800997 dlParams.className = std::move(*m.mutable_loader()->mutable_class_name());
998 dlParams.arguments = std::move(*m.mutable_loader()->mutable_arguments());
Songchun Fan3c82a302019-11-29 14:23:45 -0800999 if (!prepareDataLoader(*ifs, &dlParams)) {
1000 deleteStorage(*ifs);
1001 return false;
1002 }
1003
1004 mMounts[ifs->mountId] = std::move(ifs);
1005 return true;
1006}
1007
1008bool IncrementalService::prepareDataLoader(IncrementalService::IncFsMount& ifs,
1009 DataLoaderParamsParcel* params) {
1010 if (!mSystemReady.load(std::memory_order_relaxed)) {
1011 std::unique_lock l(ifs.lock);
1012 if (params) {
1013 if (ifs.savedDataLoaderParams) {
1014 LOG(WARNING) << "Trying to pass second set of data loader parameters, ignored it";
1015 } else {
1016 ifs.savedDataLoaderParams = std::move(*params);
1017 }
1018 } else {
1019 if (!ifs.savedDataLoaderParams) {
1020 LOG(ERROR) << "Mount " << ifs.mountId
1021 << " is broken: no data loader params (system is not ready yet)";
1022 return false;
1023 }
1024 }
1025 return true; // eventually...
1026 }
1027 if (base::GetBoolProperty("incremental.skip_loader", false)) {
1028 LOG(INFO) << "Skipped data loader because of incremental.skip_loader property";
1029 std::unique_lock l(ifs.lock);
1030 ifs.savedDataLoaderParams.reset();
1031 return true;
1032 }
1033
1034 std::unique_lock l(ifs.lock);
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001035 if (ifs.dataLoaderStatus == IDataLoaderStatusListener::DATA_LOADER_CREATED) {
Songchun Fan3c82a302019-11-29 14:23:45 -08001036 LOG(INFO) << "Skipped data loader preparation because it already exists";
1037 return true;
1038 }
1039
1040 auto* dlp = params ? params
1041 : ifs.savedDataLoaderParams ? &ifs.savedDataLoaderParams.value() : nullptr;
1042 if (!dlp) {
1043 LOG(ERROR) << "Mount " << ifs.mountId << " is broken: no data loader params";
1044 return false;
1045 }
1046 FileSystemControlParcel fsControlParcel;
1047 fsControlParcel.incremental = std::make_unique<IncrementalFileSystemControlParcel>();
Yurii Zubrytskyi4a25dfb2020-01-10 11:53:24 -08001048 fsControlParcel.incremental->cmd.reset(base::unique_fd(::dup(ifs.control.cmd)));
1049 fsControlParcel.incremental->pendingReads.reset(
1050 base::unique_fd(::dup(ifs.control.pendingReads)));
1051 fsControlParcel.incremental->log.reset(base::unique_fd(::dup(ifs.control.logs)));
Songchun Fan3c82a302019-11-29 14:23:45 -08001052 sp<IncrementalDataLoaderListener> listener = new IncrementalDataLoaderListener(*this);
1053 bool created = false;
1054 auto status = mIncrementalManager->prepareDataLoader(ifs.mountId, fsControlParcel, *dlp,
1055 listener, &created);
1056 if (!status.isOk() || !created) {
1057 LOG(ERROR) << "Failed to create a data loader for mount " << ifs.mountId;
1058 return false;
1059 }
1060 ifs.savedDataLoaderParams.reset();
1061 return true;
1062}
1063
1064binder::Status IncrementalService::IncrementalDataLoaderListener::onStatusChanged(MountId mountId,
1065 int newStatus) {
1066 std::unique_lock l(incrementalService.mLock);
1067 const auto& ifs = incrementalService.getIfsLocked(mountId);
1068 if (!ifs) {
1069 LOG(WARNING) << "Received data loader status " << int(newStatus) << " for unknown mount "
1070 << mountId;
1071 return binder::Status::ok();
1072 }
1073 ifs->dataLoaderStatus = newStatus;
1074 switch (newStatus) {
1075 case IDataLoaderStatusListener::DATA_LOADER_NO_CONNECTION: {
1076 auto now = Clock::now();
1077 if (ifs->connectionLostTime.time_since_epoch().count() == 0) {
1078 ifs->connectionLostTime = now;
1079 break;
1080 }
1081 auto duration =
1082 std::chrono::duration_cast<Seconds>(now - ifs->connectionLostTime).count();
1083 if (duration >= 10) {
1084 incrementalService.mIncrementalManager->showHealthBlockedUI(mountId);
1085 }
1086 break;
1087 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001088 case IDataLoaderStatusListener::DATA_LOADER_CONNECTION_OK: {
1089 ifs->dataLoaderStatus = IDataLoaderStatusListener::DATA_LOADER_STARTED;
1090 break;
1091 }
1092 case IDataLoaderStatusListener::DATA_LOADER_CREATED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001093 ifs->dataLoaderReady.notify_one();
1094 break;
1095 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001096 case IDataLoaderStatusListener::DATA_LOADER_DESTROYED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001097 ifs->dataLoaderStatus = IDataLoaderStatusListener::DATA_LOADER_STOPPED;
1098 incrementalService.deleteStorageLocked(*ifs, std::move(l));
1099 break;
1100 }
Alex Buynytskyy1ecfcec2019-12-17 12:10:41 -08001101 case IDataLoaderStatusListener::DATA_LOADER_STARTED: {
Songchun Fan3c82a302019-11-29 14:23:45 -08001102 break;
1103 }
1104 case IDataLoaderStatusListener::DATA_LOADER_STOPPED: {
1105 break;
1106 }
1107 default: {
1108 LOG(WARNING) << "Unknown data loader status: " << newStatus
1109 << " for mount: " << mountId;
1110 break;
1111 }
1112 }
1113
1114 return binder::Status::ok();
1115}
1116
1117} // namespace android::incremental