1 /* 2 * Copyright (C) 2022 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 <set> 19 20 #include <fruit/fruit.h> 21 22 #include "common/libs/fs/shared_fd.h" 23 #include "common/libs/utils/result.h" 24 25 namespace cuttlefish { 26 27 class InstanceLockFileManager; 28 29 enum class InUseState : char { 30 kInUse = 'I', 31 kNotInUse = 'N', 32 }; 33 34 // Replicates tempfile.gettempdir() in Python 35 std::string TempDir(); 36 37 // This class is not thread safe. 38 class InstanceLockFile { 39 public: 40 int Instance() const; 41 Result<InUseState> Status() const; 42 Result<void> Status(InUseState); 43 44 bool operator<(const InstanceLockFile&) const; 45 46 private: 47 friend class InstanceLockFileManager; 48 49 InstanceLockFile(SharedFD fd, int instance_num); 50 51 SharedFD fd_; 52 int instance_num_; 53 }; 54 55 class InstanceLockFileManager { 56 public: 57 INJECT(InstanceLockFileManager()); 58 59 Result<InstanceLockFile> AcquireLock(int instance_num); 60 Result<std::set<InstanceLockFile>> AcquireLocks(const std::set<int>& nums); 61 62 Result<std::optional<InstanceLockFile>> TryAcquireLock(int instance_num); 63 Result<std::set<InstanceLockFile>> TryAcquireLocks(const std::set<int>& nums); 64 65 // Best-effort attempt to find a free instance id. 66 Result<std::optional<InstanceLockFile>> TryAcquireUnusedLock(); 67 }; 68 69 } // namespace cuttlefish 70