• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include <string>
20 
21 #include <fruit/fruit.h>
22 
23 #include "host/commands/cvd/lock_file.h"
24 
25 namespace cuttlefish {
26 
27 // This class is not thread safe.
28 class InstanceLockFile {
29   friend class InstanceLockFileManager;
30   using LockFile = cvd_impl::LockFile;
31 
32  public:
33   int Instance() const;
34   Result<InUseState> Status() const;
35   Result<void> Status(InUseState);
36 
37   bool operator<(const InstanceLockFile&) const;
38 
39  private:
40   InstanceLockFile(LockFile&& lock_file, const int instance_num);
41   LockFile lock_file_;
42   const int instance_num_;
43 };
44 
45 class InstanceLockFileManager {
46   using LockFile = cvd_impl::LockFile;
47   using LockFileManager = cvd_impl::LockFileManager;
48 
49  public:
50   INJECT(InstanceLockFileManager());
51 
52   Result<InstanceLockFile> AcquireLock(int instance_num);
53   Result<std::set<InstanceLockFile>> AcquireLocks(const std::set<int>& nums);
54 
55   Result<std::optional<InstanceLockFile>> TryAcquireLock(int instance_num);
56   Result<std::set<InstanceLockFile>> TryAcquireLocks(const std::set<int>& nums);
57 
58   // Best-effort attempt to find a free instance id.
59   Result<std::optional<InstanceLockFile>> TryAcquireUnusedLock();
60 
61   Result<std::vector<InstanceLockFile>> LockAllAvailable();
62 
63  private:
64   /*
65    * Generate value to initialize
66    */
67   Result<std::set<int>> FindPotentialInstanceNumsFromNetDevices();
68   static Result<std::string> LockFilePath(int instance_num);
69   std::optional<std::set<int>> all_instance_nums_;
70   LockFileManager lock_file_manager_;
71 };
72 
73 }  // namespace cuttlefish
74