1 /*
2  * Copyright (C) 2018 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 #ifndef _LIBDM_TEST_UTILS_H_
18 #define _LIBDM_TEST_UTILS_H_
19 
20 #include <android-base/unique_fd.h>
21 #include <stddef.h>
22 
23 #include <chrono>
24 #include <string>
25 
26 #include <libdm/dm.h>
27 #include <libdm/dm_table.h>
28 
29 namespace android {
30 namespace dm {
31 
32 // Create a temporary in-memory file. If size is non-zero, the file will be
33 // created with a fixed size.
34 android::base::unique_fd CreateTempFile(const std::string& name, size_t size);
35 
36 // Helper to ensure that device mapper devices are released.
37 class TempDevice {
38   public:
TempDevice(const std::string & name,const DmTable & table)39     TempDevice(const std::string& name, const DmTable& table)
40         : dm_(DeviceMapper::Instance()), name_(name), valid_(false) {
41         valid_ = dm_.CreateDevice(name, table, &path_, std::chrono::seconds(5));
42     }
TempDevice(TempDevice && other)43     TempDevice(TempDevice&& other) noexcept
44         : dm_(other.dm_), name_(other.name_), path_(other.path_), valid_(other.valid_) {
45         other.valid_ = false;
46     }
~TempDevice()47     ~TempDevice() {
48         if (valid_) {
49             dm_.DeleteDevice(name_);
50         }
51     }
Destroy()52     bool Destroy() {
53         if (!valid_) {
54             return false;
55         }
56         valid_ = false;
57         return dm_.DeleteDevice(name_);
58     }
path()59     std::string path() const { return path_; }
name()60     const std::string& name() const { return name_; }
valid()61     bool valid() const { return valid_; }
62 
63     TempDevice(const TempDevice&) = delete;
64     TempDevice& operator=(const TempDevice&) = delete;
65 
66     TempDevice& operator=(TempDevice&& other) noexcept {
67         name_ = other.name_;
68         valid_ = other.valid_;
69         other.valid_ = false;
70         return *this;
71     }
72 
73   private:
74     DeviceMapper& dm_;
75     std::string name_;
76     std::string path_;
77     bool valid_;
78 };
79 
80 }  // namespace dm
81 }  // namespace android
82 
83 #endif  // _LIBDM_TEST_UTILS_H_
84