xref: /aosp_15_r20/system/core/fs_mgr/libsnapshot/snapuserd/testing/temp_device.h (revision 00c7fec1bb09f3284aad6a6f96d2f63dfc3650ad)
1 // Copyright (C) 2023 The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #pragma once
16 
17 #include <chrono>
18 #include <string>
19 
20 #include <libdm/dm.h>
21 
22 namespace android {
23 namespace snapshot {
24 
25 using android::dm::DeviceMapper;
26 using android::dm::DmTable;
27 
28 class Tempdevice {
29   public:
Tempdevice(const std::string & name,const DmTable & table)30     Tempdevice(const std::string& name, const DmTable& table)
31         : dm_(DeviceMapper::Instance()), name_(name), valid_(false) {
32         valid_ = dm_.CreateDevice(name, table, &path_, std::chrono::seconds(5));
33     }
Tempdevice(Tempdevice && other)34     Tempdevice(Tempdevice&& other) noexcept
35         : dm_(other.dm_), name_(other.name_), path_(other.path_), valid_(other.valid_) {
36         other.valid_ = false;
37     }
~Tempdevice()38     ~Tempdevice() {
39         if (valid_) {
40             dm_.DeleteDeviceIfExists(name_);
41         }
42     }
Destroy()43     bool Destroy() {
44         if (!valid_) {
45             return true;
46         }
47         valid_ = false;
48         return dm_.DeleteDeviceIfExists(name_);
49     }
path()50     const std::string& path() const { return path_; }
name()51     const std::string& name() const { return name_; }
valid()52     bool valid() const { return valid_; }
53 
54     Tempdevice(const Tempdevice&) = delete;
55     Tempdevice& operator=(const Tempdevice&) = delete;
56 
57     Tempdevice& operator=(Tempdevice&& other) noexcept {
58         name_ = other.name_;
59         valid_ = other.valid_;
60         other.valid_ = false;
61         return *this;
62     }
63 
64   private:
65     DeviceMapper& dm_;
66     std::string name_;
67     std::string path_;
68     bool valid_;
69 };
70 
71 }  // namespace snapshot
72 }  // namespace android
73