1 /* 2 * Copyright (C) 2023 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 #pragma once 17 18 #include <optional> 19 #include <set> 20 #include <string> 21 22 #include "common/libs/fs/shared_fd.h" 23 #include "common/libs/utils/result.h" 24 25 namespace cuttlefish { 26 27 enum class InUseState : char { 28 kInUse = 'I', 29 kNotInUse = 'N', 30 }; 31 32 // Replicates tempfile.gettempdir() in Python 33 std::string TempDir(); 34 35 namespace cvd_impl { 36 37 // This class is not thread safe. 38 class LockFile { 39 friend class LockFileManager; 40 41 public: LockFilePath()42 const auto& LockFilePath() const { return lock_file_path_; } 43 Result<InUseState> Status() const; 44 Result<void> Status(InUseState); 45 46 // to put this into a set 47 bool operator<(const LockFile& other) const; 48 49 private: 50 LockFile(SharedFD fd, const std::string& lock_file_path); 51 52 SharedFD fd_; 53 const std::string lock_file_path_; 54 }; 55 56 class LockFileManager { 57 public: 58 LockFileManager() = default; 59 60 Result<LockFile> AcquireLock(const std::string& lock_file_path); 61 Result<std::set<LockFile>> AcquireLocks( 62 const std::set<std::string>& lock_file_paths); 63 64 Result<std::optional<LockFile>> TryAcquireLock( 65 const std::string& lock_file_path); 66 Result<std::set<LockFile>> TryAcquireLocks( 67 const std::set<std::string>& lock_file_paths); 68 69 // Best-effort attempt to find a free instance id. 70 Result<std::optional<LockFile>> TryAcquireUnusedLock(); 71 72 static Result<SharedFD> OpenLockFile(const std::string& file_path); 73 }; 74 75 } // namespace cvd_impl 76 } // namespace cuttlefish 77