-
Notifications
You must be signed in to change notification settings - Fork 0
/
baggageclaim.go
327 lines (286 loc) · 9.79 KB
/
baggageclaim.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
package driver
import (
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"code.cloudfoundry.org/lager"
bclient "github.com/concourse/baggageclaim/client"
"github.com/golang/glog"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"k8s.io/mount-utils"
utilexec "k8s.io/utils/exec"
timestamp "github.com/golang/protobuf/ptypes/timestamp"
)
const (
kib int64 = 1024
mib int64 = kib * 1024
gib int64 = mib * 1024
gib100 int64 = gib * 100
tib int64 = gib * 1024
tib100 int64 = tib * 100
)
type hostPath struct {
name string
nodeID string
version string
endpoint string
ephemeral bool
maxVolumesPerNode int64
ids *identityServer
ns *nodeServer
cs *controllerServer
}
type baggageclaimNode struct {
name string
nodeID string
version string
endpoint string
ephemeral bool //TODO: always false? remove this maybe? We want volumes to persist...
maxVolumesPerNode int64 //TODO: can we remove this?
ids *identityServer
ns *nodeServer
cs *controllerServer
}
type hostPathVolume struct { //TODO: remove
VolName string `json:"volName"`
VolID string `json:"volID"`
VolSize int64 `json:"volSize"`
VolPath string `json:"volPath"`
VolAccessType accessType `json:"volAccessType"`
ParentVolID string `json:"parentVolID,omitempty"`
ParentSnapID string `json:"parentSnapID,omitempty"`
Ephemeral bool `json:"ephemeral"`
}
type hostPathSnapshot struct { //TODO: remove
Name string `json:"name"`
Id string `json:"id"`
VolID string `json:"volID"`
Path string `json:"path"`
CreationTime timestamp.Timestamp `json:"creationTime"`
SizeBytes int64 `json:"sizeBytes"`
ReadyToUse bool `json:"readyToUse"`
}
var (
vendorVersion = "dev"
hostPathVolumes map[string]hostPathVolume //TODO: remove
hostPathVolumeSnapshots map[string]hostPathSnapshot //TODO: remove
)
const (
// Directory where data for volumes and snapshots are persisted.
// This can be ephemeral within the container or persisted if
// backed by a Pod volume.
dataRoot = "/csi-data-dir" //TODO: remove
// Extension with which snapshot files will be saved.
snapshotExt = ".snap" //TODO: remove
)
func init() {
hostPathVolumes = map[string]hostPathVolume{} //TODO: remove
hostPathVolumeSnapshots = map[string]hostPathSnapshot{} //TODO: remove
}
func NewHostPathDriver(driverName, nodeID, endpoint string, ephemeral bool, maxVolumesPerNode int64, version string) (*hostPath, error) {
if driverName == "" {
return nil, errors.New("no driver name provided")
}
if nodeID == "" {
return nil, errors.New("no node id provided")
}
if endpoint == "" {
return nil, errors.New("no driver endpoint provided")
}
if version != "" {
vendorVersion = version
}
if err := os.MkdirAll(dataRoot, 0750); err != nil {
return nil, fmt.Errorf("failed to create dataRoot: %v", err)
}
glog.Infof("Driver: %v ", driverName)
glog.Infof("Version: %s", vendorVersion)
return &hostPath{
name: driverName,
version: vendorVersion,
nodeID: nodeID,
endpoint: endpoint,
ephemeral: ephemeral,
maxVolumesPerNode: maxVolumesPerNode,
}, nil
}
func getSnapshotID(file string) (bool, string) {
glog.V(4).Infof("file: %s", file)
// Files with .snap extension are volumesnapshot files.
// e.g. foo.snap, foo.bar.snap
if filepath.Ext(file) == snapshotExt {
return true, strings.TrimSuffix(file, snapshotExt)
}
return false, ""
}
func discoverExistingSnapshots() {
glog.V(4).Infof("discovering existing snapshots in %s", dataRoot)
files, err := ioutil.ReadDir(dataRoot)
if err != nil {
glog.Errorf("failed to discover snapshots under %s: %v", dataRoot, err)
}
for _, file := range files {
isSnapshot, snapshotID := getSnapshotID(file.Name())
if isSnapshot {
glog.V(4).Infof("adding snapshot %s from file %s", snapshotID, getSnapshotPath(snapshotID))
hostPathVolumeSnapshots[snapshotID] = hostPathSnapshot{
Id: snapshotID,
Path: getSnapshotPath(snapshotID),
ReadyToUse: true,
}
}
}
}
func (hp *hostPath) Run() {
bagClient := bclient.NewWithHTTPClient("http://127.0.0.1:7788",
&http.Client{
Transport: &http.Transport{
ResponseHeaderTimeout: 1 * time.Minute,
},
// All calls are local so if we hit this something is probably
// really broken
Timeout: 5 * time.Minute,
})
mounter := mount.New("")
// Create GRPC servers
hp.ids = NewIdentityServer(hp.name, hp.version)
hp.ns = NewNodeServer(hp.nodeID, hp.maxVolumesPerNode, bagClient, mounter, lager.NewLogger("temp"))
hp.cs = NewControllerServer(hp.ephemeral, hp.nodeID)
discoverExistingSnapshots()
s := NewNonBlockingGRPCServer()
s.Start(hp.endpoint, hp.ids, hp.cs, hp.ns)
s.Wait()
}
func getVolumeByID(volumeID string) (hostPathVolume, error) {
if hostPathVol, ok := hostPathVolumes[volumeID]; ok {
return hostPathVol, nil
}
return hostPathVolume{}, fmt.Errorf("volume id %s does not exist in the volumes list", volumeID)
}
func getVolumeByName(volName string) (hostPathVolume, error) {
for _, hostPathVol := range hostPathVolumes {
if hostPathVol.VolName == volName {
return hostPathVol, nil
}
}
return hostPathVolume{}, fmt.Errorf("volume name %s does not exist in the volumes list", volName)
}
func getSnapshotByName(name string) (hostPathSnapshot, error) {
for _, snapshot := range hostPathVolumeSnapshots {
if snapshot.Name == name {
return snapshot, nil
}
}
return hostPathSnapshot{}, fmt.Errorf("snapshot name %s does not exist in the snapshots list", name)
}
// getVolumePath returns the canonical path for hostpath volume
func getVolumePath(volID string) string {
return filepath.Join(dataRoot, volID)
}
// updateVolume updates the existing hostpath volume.
func updateHostpathVolume(volID string, volume hostPathVolume) error {
glog.V(4).Infof("updating hostpath volume: %s", volID)
if _, err := getVolumeByID(volID); err != nil {
return err
}
hostPathVolumes[volID] = volume
return nil
}
// hostPathIsEmpty is a simple check to determine if the specified hostpath directory
// is empty or not.
func hostPathIsEmpty(p string) (bool, error) {
f, err := os.Open(p)
if err != nil {
return true, fmt.Errorf("unable to open hostpath volume, error: %v", err)
}
defer f.Close()
_, err = f.Readdir(1)
if err == io.EOF {
return true, nil
}
return false, err
}
// loadFromSnapshot populates the given destPath with data from the snapshotID
func loadFromSnapshot(size int64, snapshotId, destPath string, mode accessType) error {
snapshot, ok := hostPathVolumeSnapshots[snapshotId]
if !ok {
return status.Errorf(codes.NotFound, "cannot find snapshot %v", snapshotId)
}
if snapshot.ReadyToUse != true {
return status.Errorf(codes.Internal, "snapshot %v is not yet ready to use.", snapshotId)
}
if snapshot.SizeBytes > size {
return status.Errorf(codes.InvalidArgument, "snapshot %v size %v is greater than requested volume size %v", snapshotId, snapshot.SizeBytes, size)
}
snapshotPath := snapshot.Path
var cmd []string
switch mode {
case mountAccess:
cmd = []string{"tar", "zxvf", snapshotPath, "-C", destPath}
case blockAccess:
cmd = []string{"dd", "if=" + snapshotPath, "of=" + destPath}
default:
return status.Errorf(codes.InvalidArgument, "unknown accessType: %d", mode)
}
executor := utilexec.New()
out, err := executor.Command(cmd[0], cmd[1:]...).CombinedOutput()
if err != nil {
return status.Errorf(codes.Internal, "failed pre-populate data from snapshot %v: %v: %s", snapshotId, err, out)
}
return nil
}
// loadFromVolume populates the given destPath with data from the srcVolumeID
func loadFromVolume(size int64, srcVolumeId, destPath string, mode accessType) error {
hostPathVolume, ok := hostPathVolumes[srcVolumeId]
if !ok {
return status.Error(codes.NotFound, "source volumeId does not exist, are source/destination in the same storage class?")
}
if hostPathVolume.VolSize > size {
return status.Errorf(codes.InvalidArgument, "volume %v size %v is greater than requested volume size %v", srcVolumeId, hostPathVolume.VolSize, size)
}
if mode != hostPathVolume.VolAccessType {
return status.Errorf(codes.InvalidArgument, "volume %v mode is not compatible with requested mode", srcVolumeId)
}
switch mode {
case mountAccess:
return loadFromFilesystemVolume(hostPathVolume, destPath)
case blockAccess:
return loadFromBlockVolume(hostPathVolume, destPath)
default:
return status.Errorf(codes.InvalidArgument, "unknown accessType: %d", mode)
}
}
func loadFromFilesystemVolume(hostPathVolume hostPathVolume, destPath string) error {
srcPath := hostPathVolume.VolPath
isEmpty, err := hostPathIsEmpty(srcPath)
if err != nil {
return status.Errorf(codes.Internal, "failed verification check of source hostpath volume %v: %v", hostPathVolume.VolID, err)
}
// If the source hostpath volume is empty it's a noop and we just move along, otherwise the cp call will fail with a a file stat error DNE
if !isEmpty {
args := []string{"-a", srcPath + "/.", destPath + "/"}
executor := utilexec.New()
out, err := executor.Command("cp", args...).CombinedOutput()
if err != nil {
return status.Errorf(codes.Internal, "failed pre-populate data from volume %v: %v: %s", hostPathVolume.VolID, err, out)
}
}
return nil
}
func loadFromBlockVolume(hostPathVolume hostPathVolume, destPath string) error {
srcPath := hostPathVolume.VolPath
args := []string{"if=" + srcPath, "of=" + destPath}
executor := utilexec.New()
out, err := executor.Command("dd", args...).CombinedOutput()
if err != nil {
return status.Errorf(codes.Internal, "failed pre-populate data from volume %v: %v: %s", hostPathVolume.VolID, err, out)
}
return nil
}