forked from firecracker-microvm/firecracker-containerd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdrive_handler.go
284 lines (235 loc) · 7.13 KB
/
drive_handler.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License"). You may
// not use this file except in compliance with the License. A copy of the
// License is located at
//
// http://aws.amazon.com/apache2.0/
//
// or in the "license" file accompanying this file. This file is distributed
// on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
// express or implied. See the License for the specific language governing
// permissions and limitations under the License.
package main
import (
"context"
"fmt"
"os"
"path/filepath"
"strings"
"time"
"github.com/containerd/containerd/log"
"github.com/containerd/containerd/mount"
"github.com/containerd/containerd/protobuf/types"
"github.com/firecracker-microvm/firecracker-containerd/internal"
drivemount "github.com/firecracker-microvm/firecracker-containerd/proto/service/drivemount/ttrpc"
)
const (
blockPath = "/sys/block"
drivePath = "/dev"
blockMajorMinor = "dev"
)
var (
bannedSystemDirs = []string{
"/proc",
"/sys",
"/dev",
}
)
type drive struct {
Name string
DriveID string
MajorMinor string
DrivePath string
}
type driveHandler struct {
// drives is a mapping to all the stub drives
drives map[string]drive
// BlockPath contains the location of the block subdirectory under the sysfs
// mount point.
BlockPath string
// DrivePath should contain the location of the drive block device nodes.
DrivePath string
}
var _ drivemount.DriveMounterService = &driveHandler{}
func newDriveHandler(blockPath, drivePath string) (*driveHandler, error) {
d := &driveHandler{
drives: map[string]drive{},
BlockPath: blockPath,
DrivePath: drivePath,
}
err := d.discoverDrives()
if err != nil {
return nil, err
}
return d, nil
}
func (dh driveHandler) GetDrive(id string) (drive, bool) {
v, ok := dh.drives[id]
return v, ok
}
// discoverDrives will iterate the block path in the sys directory to retrieve all
// stub block devices.
func (dh *driveHandler) discoverDrives() error {
names, err := getListOfBlockDeviceNames(dh.BlockPath)
if err != nil {
return err
}
drives := map[string]drive{}
for _, name := range names {
d, err := dh.buildDrive(name)
if err != nil {
return err
}
if !isStubDrive(d) {
continue
}
f, err := os.Open(d.Path())
if err != nil {
return err
}
d.DriveID, err = internal.ParseStubContent(f)
f.Close()
if err != nil {
return err
}
drives[d.DriveID] = d
}
dh.drives = drives
return nil
}
func (d drive) Path() string {
return filepath.Join(d.DrivePath, d.Name)
}
func getListOfBlockDeviceNames(path string) ([]string, error) {
names := []string{}
infos, err := os.ReadDir(path)
if err != nil {
return nil, err
}
for _, info := range infos {
names = append(names, info.Name())
}
return names, nil
}
// buildDrive uses the /sys/block folder to check a given name's block major
// and minor, and block size.
func (dh driveHandler) buildDrive(name string) (drive, error) {
d := drive{
Name: name,
DrivePath: dh.DrivePath,
}
majorMinorStr, err := os.ReadFile(filepath.Join(dh.BlockPath, name, blockMajorMinor))
if err != nil {
return d, err
}
d.MajorMinor = strings.TrimSpace(string(majorMinorStr))
return d, nil
}
// isStubDrive will check to see if a given drive is a stub drive.
func isStubDrive(d drive) bool {
f, err := os.Open(d.Path())
if err != nil {
return false
}
defer f.Close()
return internal.IsStubDrive(f)
}
func (dh driveHandler) MountDrive(ctx context.Context, req *drivemount.MountDriveRequest) (*types.Empty, error) {
logger := log.G(ctx)
logger.Debugf("%+v", req.String())
logger = logger.WithField("drive_id", req.DriveID)
drive, ok := dh.GetDrive(req.DriveID)
if !ok {
return nil, fmt.Errorf("drive %q could not be found", req.DriveID)
}
logger = logger.WithField("drive_path", drive.Path())
// Do a basic check that we won't be mounting over any important system directories
if err := isSystemDir(req.DestinationPath); err != nil {
return nil, err
}
err := os.MkdirAll(req.DestinationPath, 0700)
if err != nil {
return nil, fmt.Errorf("failed to create drive mount destination %q: %w", req.DestinationPath, err)
}
// Retry the mount in the case of failure a fixed number of times. This works around a rare issue
// where we get to this mount attempt before the guest OS has realized a drive was patched:
// https://github.com/firecracker-microvm/firecracker-containerd/issues/214
const (
maxRetries = 100
retryDelay = 10 * time.Millisecond
)
for i := 0; i < maxRetries; i++ {
err := mount.All([]mount.Mount{{
Source: drive.Path(),
Type: req.FilesytemType,
Options: req.Options,
}}, req.DestinationPath)
if err == nil {
return &types.Empty{}, nil
}
if isRetryableMountError(err) {
logger.WithError(err).Warnf("retryable failure mounting drive")
time.Sleep(retryDelay)
continue
}
return nil, fmt.Errorf("non-retryable failure mounting drive from %q to %q: %w", drive.Path(), req.DestinationPath, err)
}
return nil, fmt.Errorf("exhausted retries mounting drive from %q to %q", drive.Path(), req.DestinationPath)
}
func (dh driveHandler) UnmountDrive(ctx context.Context, req *drivemount.UnmountDriveRequest) (*types.Empty, error) {
drive, ok := dh.GetDrive(req.DriveID)
if !ok {
return nil, fmt.Errorf("drive %q could not be found", req.DriveID)
}
err := mount.Unmount(drive.Path(), 0)
if err == nil {
return &types.Empty{}, nil
}
return nil, fmt.Errorf("failed to unmount drive %q: %w", drive.Path(), err)
}
func isSystemDir(path string) error {
resolvedDest, err := evalAnySymlinks(path)
if err != nil {
return fmt.Errorf("failed to evaluate any symlinks in drive unmount destination %q: %w", path, err)
}
for _, systemDir := range bannedSystemDirs {
if isOrUnderDir(resolvedDest, systemDir) {
return fmt.Errorf("drive mount destination %q resolves to path %q under banned system directory %q", path, resolvedDest, systemDir)
}
}
return nil
}
// evalAnySymlinks is similar to filepath.EvalSymlinks, except it will not return an error if part of the
// provided path does not exist. It will evaluate symlinks present in the path up to a component that doesn't
// exist, at which point it will just append the rest of the provided path to what has been resolved so far.
// We validate earlier that input to this function is an absolute path.
func evalAnySymlinks(path string) (string, error) {
curPath := "/"
pathSplit := strings.Split(filepath.Clean(path), "/")
for len(pathSplit) > 0 {
curPath = filepath.Join(curPath, pathSplit[0])
pathSplit = pathSplit[1:]
resolvedPath, err := filepath.EvalSymlinks(curPath)
if os.IsNotExist(err) {
return filepath.Join(append([]string{curPath}, pathSplit...)...), nil
}
if err != nil {
return "", err
}
curPath = resolvedPath
}
return curPath, nil
}
// returns whether the given path is the provided baseDir or is under it
func isOrUnderDir(path, baseDir string) bool {
path = filepath.Clean(path)
baseDir = filepath.Clean(baseDir)
if baseDir == "/" {
return true
}
if path == baseDir {
return true
}
return strings.HasPrefix(path, baseDir+"/")
}