forked from k3s-io/kubernetes
-
Notifications
You must be signed in to change notification settings - Fork 0
/
volume.go
430 lines (391 loc) · 12 KB
/
volume.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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
/*
Copyright 2014 Google Inc. 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.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License 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 volume
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"strconv"
"github.com/GoogleCloudPlatform/kubernetes/pkg/api"
"github.com/GoogleCloudPlatform/kubernetes/pkg/util/exec"
"github.com/golang/glog"
)
var ErrUnsupportedVolumeType = errors.New("unsupported volume type")
// Interface is a directory used by pods or hosts.
// All method implementations of methods in the volume interface must be idempotent.
type Interface interface {
// GetPath returns the directory path the volume is mounted to.
GetPath() string
}
// Builder interface provides method to set up/mount the volume.
type Builder interface {
// Uses Interface to provide the path for Docker binds.
Interface
// SetUp prepares and mounts/unpacks the volume to a directory path.
SetUp() error
}
// Cleaner interface provides method to cleanup/unmount the volumes.
type Cleaner interface {
// TearDown unmounts the volume and removes traces of the SetUp procedure.
TearDown() error
}
type gcePersistentDiskUtil interface {
// Attaches the disk to the kubelet's host machine.
AttachDisk(PD *GCEPersistentDisk) error
// Detaches the disk from the kubelet's host machine.
DetachDisk(PD *GCEPersistentDisk, devicePath string) error
}
// Mounters wrap os/system specific calls to perform mounts.
type mounter interface {
Mount(source string, target string, fstype string, flags uintptr, data string) error
Unmount(target string, flags int) error
// RefCount returns the device path for the source disk of a volume, and
// the number of references to that target disk.
RefCount(vol Interface) (string, int, error)
}
// HostDir volumes represent a bare host directory mount.
// The directory in Path will be directly exposed to the container.
type HostDir struct {
Path string
}
// SetUp implements interface definitions, even though host directory
// mounts don't require any setup or cleanup.
func (hostVol *HostDir) SetUp() error {
return nil
}
func (hostVol *HostDir) GetPath() string {
return hostVol.Path
}
type execInterface interface {
ExecCommand(cmd []string, dir string) ([]byte, error)
}
type GitDir struct {
Source string
Revision string
PodID string
RootDir string
Name string
exec exec.Interface
}
func newGitRepo(volume *api.Volume, podID, rootDir string) *GitDir {
return &GitDir{
Source: volume.Source.GitRepo.Repository,
Revision: volume.Source.GitRepo.Revision,
PodID: podID,
RootDir: rootDir,
Name: volume.Name,
exec: exec.New(),
}
}
func (g *GitDir) ExecCommand(command string, args []string, dir string) ([]byte, error) {
cmd := g.exec.Command(command, args...)
cmd.SetDir(dir)
return cmd.CombinedOutput()
}
func (g *GitDir) SetUp() error {
volumePath := g.GetPath()
if err := os.MkdirAll(volumePath, 0750); err != nil {
return err
}
if _, err := g.ExecCommand("git", []string{"clone", g.Source}, g.GetPath()); err != nil {
return err
}
files, err := ioutil.ReadDir(g.GetPath())
if err != nil {
return err
}
if len(g.Revision) == 0 {
return nil
}
if len(files) != 1 {
return fmt.Errorf("unexpected directory contents: %v", files)
}
dir := path.Join(g.GetPath(), files[0].Name())
if _, err := g.ExecCommand("git", []string{"checkout", g.Revision}, dir); err != nil {
return err
}
if _, err := g.ExecCommand("git", []string{"reset", "--hard"}, dir); err != nil {
return err
}
return nil
}
func (g *GitDir) GetPath() string {
return path.Join(g.RootDir, g.PodID, "volumes", "git", g.Name)
}
// TearDown simply deletes everything in the directory.
func (g *GitDir) TearDown() error {
tmpDir, err := renameDirectory(g.GetPath(), g.Name+"~deleting")
if err != nil {
return err
}
err = os.RemoveAll(tmpDir)
if err != nil {
return err
}
return nil
}
// EmptyDir volumes are temporary directories exposed to the pod.
// These do not persist beyond the lifetime of a pod.
type EmptyDir struct {
Name string
PodID string
RootDir string
}
// SetUp creates new directory.
func (emptyDir *EmptyDir) SetUp() error {
path := emptyDir.GetPath()
return os.MkdirAll(path, 0750)
}
func (emptyDir *EmptyDir) GetPath() string {
return path.Join(emptyDir.RootDir, emptyDir.PodID, "volumes", "empty", emptyDir.Name)
}
func renameDirectory(oldPath, newName string) (string, error) {
newPath, err := ioutil.TempDir(path.Dir(oldPath), newName)
if err != nil {
return "", err
}
err = os.Rename(oldPath, newPath)
if err != nil {
return "", err
}
return newPath, nil
}
// TearDown simply deletes everything in the directory.
func (emptyDir *EmptyDir) TearDown() error {
tmpDir, err := renameDirectory(emptyDir.GetPath(), emptyDir.Name+".deleting~")
if err != nil {
return err
}
err = os.RemoveAll(tmpDir)
if err != nil {
return err
}
return nil
}
// createHostDir interprets API volume as a HostDir.
func createHostDir(volume *api.Volume) *HostDir {
return &HostDir{volume.Source.HostDir.Path}
}
// GCEPersistentDisk volumes are disk resources provided by Google Compute Engine
// that are attached to the kubelet's host machine and exposed to the pod.
type GCEPersistentDisk struct {
Name string
PodID string
RootDir string
// Unique identifier of the PD, used to find the disk resource in the provider.
PDName string
// Filesystem type, optional.
FSType string
// Specifies the partition to mount
Partition string
// Specifies whether the disk will be attached as ReadOnly.
ReadOnly bool
// Utility interface that provides API calls to the provider to attach/detach disks.
util gcePersistentDiskUtil
// Mounter interface that provides system calls to mount the disks.
mounter mounter
}
func (PD *GCEPersistentDisk) GetPath() string {
return path.Join(PD.RootDir, PD.PodID, "volumes", "gce-pd", PD.Name)
}
// Attaches the disk and bind mounts to the volume path.
func (PD *GCEPersistentDisk) SetUp() error {
// TODO: handle failed mounts here.
if _, err := os.Stat(PD.GetPath()); !os.IsNotExist(err) {
return nil
}
err := PD.util.AttachDisk(PD)
if err != nil {
return err
}
flags := uintptr(0)
if PD.ReadOnly {
flags = MOUNT_MS_RDONLY
}
//Perform a bind mount to the full path to allow duplicate mounts of the same PD.
if _, err = os.Stat(PD.GetPath()); os.IsNotExist(err) {
err = os.MkdirAll(PD.GetPath(), 0750)
if err != nil {
return err
}
globalPDPath := makeGlobalPDName(PD.RootDir, PD.PDName, PD.ReadOnly)
err = PD.mounter.Mount(globalPDPath, PD.GetPath(), "", MOUNT_MS_BIND|flags, "")
if err != nil {
os.RemoveAll(PD.GetPath())
return err
}
}
return nil
}
// Unmounts the bind mount, and detaches the disk only if the PD
// resource was the last reference to that disk on the kubelet.
func (PD *GCEPersistentDisk) TearDown() error {
devicePath, refCount, err := PD.mounter.RefCount(PD)
if err != nil {
return err
}
if err := PD.mounter.Unmount(PD.GetPath(), 0); err != nil {
return err
}
refCount--
if err := os.RemoveAll(PD.GetPath()); err != nil {
return err
}
if err != nil {
return err
}
// If refCount is 1, then all bind mounts have been removed, and the
// remaining reference is the global mount. It is safe to detach.
if refCount == 1 {
if err := PD.util.DetachDisk(PD, devicePath); err != nil {
return err
}
}
return nil
}
//TODO(jonesdl) prevent name collisions by using designated pod space as well.
// Ex. (ROOT_DIR)/pods/...
func makeGlobalPDName(rootDir, devName string, readOnly bool) string {
var mode string
if readOnly {
mode = "ro"
} else {
mode = "rw"
}
return path.Join(rootDir, "global", "pd", mode, devName)
}
// createEmptyDir interprets API volume as an EmptyDir.
func createEmptyDir(volume *api.Volume, podID string, rootDir string) *EmptyDir {
return &EmptyDir{volume.Name, podID, rootDir}
}
// Interprets API volume as a PersistentDisk
func createGCEPersistentDisk(volume *api.Volume, podID string, rootDir string) (*GCEPersistentDisk, error) {
PDName := volume.Source.GCEPersistentDisk.PDName
FSType := volume.Source.GCEPersistentDisk.FSType
partition := strconv.Itoa(volume.Source.GCEPersistentDisk.Partition)
if partition == "0" {
partition = ""
}
readOnly := volume.Source.GCEPersistentDisk.ReadOnly
// TODO: move these up into the Kubelet.
util := &GCEDiskUtil{}
mounter := &DiskMounter{}
return &GCEPersistentDisk{
Name: volume.Name,
PodID: podID,
RootDir: rootDir,
PDName: PDName,
FSType: FSType,
Partition: partition,
ReadOnly: readOnly,
util: util,
mounter: mounter}, nil
}
// CreateVolumeBuilder returns a Builder capable of mounting a volume described by an
// *api.Volume, or an error.
func CreateVolumeBuilder(volume *api.Volume, podID string, rootDir string) (Builder, error) {
source := volume.Source
// TODO(jonesdl) We will want to throw an error here when we no longer
// support the default behavior.
if source == nil {
return nil, nil
}
var vol Builder
var err error
// TODO(jonesdl) We should probably not check every pointer and directly
// resolve these types instead.
if source.HostDir != nil {
vol = createHostDir(volume)
} else if source.EmptyDir != nil {
vol = createEmptyDir(volume, podID, rootDir)
} else if source.GCEPersistentDisk != nil {
vol, err = createGCEPersistentDisk(volume, podID, rootDir)
if err != nil {
return nil, err
}
} else if source.GitRepo != nil {
vol = newGitRepo(volume, podID, rootDir)
} else {
return nil, ErrUnsupportedVolumeType
}
return vol, nil
}
// CreateVolumeCleaner returns a Cleaner capable of tearing down a volume.
func CreateVolumeCleaner(kind string, name string, podID string, rootDir string) (Cleaner, error) {
switch kind {
case "empty":
return &EmptyDir{name, podID, rootDir}, nil
case "gce-pd":
return &GCEPersistentDisk{
Name: name,
PodID: podID,
RootDir: rootDir,
util: &GCEDiskUtil{},
mounter: &DiskMounter{}}, nil
case "git":
return &GitDir{
Name: name,
PodID: podID,
RootDir: rootDir,
}, nil
default:
return nil, ErrUnsupportedVolumeType
}
}
// GetCurrentVolumes examines directory structure to determine volumes that are
// presently active and mounted. Returns a map of Cleaner types.
func GetCurrentVolumes(rootDirectory string) map[string]Cleaner {
currentVolumes := make(map[string]Cleaner)
podIDDirs, err := ioutil.ReadDir(rootDirectory)
if err != nil {
glog.Errorf("Could not read directory %s: %v", rootDirectory, err)
}
// Volume information is extracted from the directory structure:
// (ROOT_DIR)/(POD_ID)/volumes/(VOLUME_KIND)/(VOLUME_NAME)
for _, podIDDir := range podIDDirs {
if !podIDDir.IsDir() {
continue
}
podID := podIDDir.Name()
podIDPath := path.Join(rootDirectory, podID, "volumes")
if _, err := os.Stat(podIDPath); os.IsNotExist(err) {
continue
}
volumeKindDirs, err := ioutil.ReadDir(podIDPath)
if err != nil {
glog.Errorf("Could not read directory %s: %v", podIDPath, err)
}
for _, volumeKindDir := range volumeKindDirs {
volumeKind := volumeKindDir.Name()
volumeKindPath := path.Join(podIDPath, volumeKind)
volumeNameDirs, err := ioutil.ReadDir(volumeKindPath)
if err != nil {
glog.Errorf("Could not read directory %s: %v", volumeKindPath, err)
}
for _, volumeNameDir := range volumeNameDirs {
volumeName := volumeNameDir.Name()
identifier := path.Join(podID, volumeName)
// TODO(thockin) This should instead return a reference to an extant volume object
cleaner, err := CreateVolumeCleaner(volumeKind, volumeName, podID, rootDirectory)
if err != nil {
glog.Errorf("Could not create volume cleaner for %s: %v", volumeNameDir.Name(), err)
continue
}
currentVolumes[identifier] = cleaner
}
}
}
return currentVolumes
}