/
volumelock.go
254 lines (225 loc) · 7.15 KB
/
volumelock.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
// Copyright 2020 Google LLC
//
// 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 driverd
import (
"context"
"fmt"
"sync"
diskrpc "github.com/aleofreddi/csi-sanlock-lvm/pkg/diskrpc"
"github.com/aleofreddi/csi-sanlock-lvm/pkg/proto" // FIXME
pb "github.com/aleofreddi/csi-sanlock-lvm/pkg/proto"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"k8s.io/klog"
)
type VolumeLocker interface {
// Lock the given volume for the given operation.
//
// Volume locks are reentrant per volume (but not per <volume, op> pairs),
// that is one can lock the same volume with multiple ops.
LockVolume(ctx context.Context, vol VolumeRef, op string) error
// Unlock a volume for a given <vol, op> pair.
UnlockVolume(ctx context.Context, vol VolumeRef, op string) error
// Retrieve the owner mailbox and name for a volume, if any.
GetOwner(ctx context.Context, ref VolumeRef) (diskrpc.MailBoxID, string, error)
}
type volumeLocker struct {
baseServer
nodeName string
locks map[string]map[string]struct{}
mutex *sync.Mutex
}
const (
defaultLockOp = "stage"
)
func NewVolumeLocker(lvmctrld pb.LvmCtrldClient, nodeName string) (VolumeLocker, error) {
bs, err := newBaseServer(lvmctrld)
if err != nil {
return nil, err
}
vl := &volumeLocker{
baseServer: *bs,
nodeName: nodeName,
locks: map[string]map[string]struct{}{},
mutex: &sync.Mutex{},
}
ctx := context.Background()
if err = vl.sync(ctx); err != nil {
return nil, fmt.Errorf("failed to sync LVM state: %v", err)
}
return vl, nil
}
func (vl *volumeLocker) LockVolume(ctx context.Context, vol VolumeRef, op string) error {
vl.mutex.Lock()
defer vl.mutex.Unlock()
key := vol.VgLv()
m, ok := vl.locks[key]
if !ok {
m = make(map[string]struct{})
vl.locks[key] = m
}
if len(m) > 0 {
m[op] = struct{}{}
return nil
}
// Lock the volume.
_, err := vl.lvmctrld.LvChange(ctx, &proto.LvChangeRequest{
Target: []string{vol.VgLv()},
Activate: proto.LvActivationMode_LV_ACTIVATION_MODE_ACTIVE_EXCLUSIVE,
})
if err != nil {
return status.Errorf(status.Code(err), "failed to lock volume %s: %v", vol, err)
}
// Update tags.
err = vl.setOwner(ctx, vol, &vl.nodeID, &vl.nodeName)
if err != nil {
// Try to unlock the volume.
_, err2 := vl.lvmctrld.LvChange(ctx, &proto.LvChangeRequest{
Target: []string{vol.VgLv()},
Activate: proto.LvActivationMode_LV_ACTIVATION_MODE_DEACTIVATE,
})
if err2 != nil {
klog.Errorf("Failed to unlock volume %s: %v (ignoring error)", vol, err2)
}
return status.Errorf(status.Code(err), "failed to update owner tags on volume %s: %v", vol, err)
}
m[op] = struct{}{}
return nil
}
func (vl *volumeLocker) UnlockVolume(ctx context.Context, vol VolumeRef, op string) error {
vl.mutex.Lock()
defer vl.mutex.Unlock()
// If volume is not locked, return.
key := vol.VgLv()
m, ok := vl.locks[key]
if !ok {
return nil
}
delete(m, op)
if len(m) > 0 {
return nil
}
// Remove owner tags.
err := vl.setOwner(ctx, vol, nil, nil)
if err != nil {
return err
}
// Unlock the volume.
_, err = vl.lvmctrld.LvChange(ctx, &proto.LvChangeRequest{
Target: []string{vol.VgLv()},
Activate: proto.LvActivationMode_LV_ACTIVATION_MODE_DEACTIVATE,
})
if err != nil {
return status.Errorf(status.Code(err), "failed to unlock volume %s: %v", vol, err)
}
delete(vl.locks, key)
return nil
}
// Retrieve the owner node for a given volume.
func (vl *volumeLocker) GetOwner(ctx context.Context, ref VolumeRef) (diskrpc.MailBoxID, string, error) {
// Fetch the volume and get its tags.
vol, err := vl.fetch(ctx, &ref)
if err != nil {
return 0, "", status.Errorf(codes.Internal, "failed to list logical volume %s: %v", vol, err)
}
tags, err := vol.Tags()
if err != nil {
return 0, "", status.Errorf(codes.Internal, "failed to decode tags on volume %s: %v", vol, err)
}
var nodeID uint16
if v, ok := tags[ownerIdTagKey]; ok {
nodeID, err = nodeIDFromString(v)
if err != nil {
return 0, "", status.Errorf(codes.Internal, "failed to parse owner id tag on volume %s: %v", vol, err)
}
}
nodeName, _ := tags[ownerNodeTagKey]
return diskrpc.MailBoxID(nodeID), nodeName, nil
}
// Update the owner tag of a volume, removing any stale owner tag and replacing
// them with a new ownerID entry (if present).
//
// Calling this function with a nil ownerID will cause it to remove all owner tags.
func (vl *volumeLocker) setOwner(ctx context.Context, ref VolumeRef, ownerID *uint16, ownerNode *string) error {
// Fetch the volume and get its tags
vol, err := vl.fetch(ctx, &ref)
if err != nil {
return err
}
tags, err := vol.Tags()
if err != nil {
return err
}
// Decide which tags to add/remove
var addTags, delTags []string
pOwnerID, ok := tags[ownerIdTagKey]
if ok && (ownerID == nil || pOwnerID != nodeIDToString(*ownerID)) {
delTags = append(delTags, encodeTagKV(ownerIdTagKey, pOwnerID))
}
pOwnerNode, ok := tags[ownerNodeTagKey]
if ok && (ownerNode == nil || pOwnerNode != *ownerNode) {
delTags = append(delTags, encodeTagKV(ownerNodeTagKey, pOwnerNode))
}
if ownerID != nil {
addTags = append(addTags, encodeTagKV(ownerIdTagKey, nodeIDToString(*ownerID)))
}
if ownerNode != nil {
addTags = append(addTags, encodeTagKV(ownerNodeTagKey, *ownerNode))
}
// Update volume tags
if len(addTags) == 0 && len(delTags) == 0 {
return nil
}
_, err = vl.lvmctrld.LvChange(ctx, &pb.LvChangeRequest{
Target: []string{vol.VgLv()},
AddTag: addTags,
DelTag: delTags,
})
return err
}
func (vl *volumeLocker) sync(ctx context.Context) error {
vl.mutex.Lock()
defer vl.mutex.Unlock()
klog.Infof("Syncing LVM status")
// Find all active volumes.
lvs, err := vl.lvmctrld.Lvs(ctx, &pb.LvsRequest{
Select: fmt.Sprintf("lv_name=~^%s && lv_active=active", volumeLvPrefix),
})
if err != nil {
return fmt.Errorf("failed to list logical volumes: %v", err)
}
for _, lv := range lvs.Lvs {
vol := NewVolumeRefFromLv(lv)
// Try to deactivate volume if it is not opened
if lv.LvDeviceOpen != pb.LvDeviceOpen_LV_DEVICE_OPEN_OPEN {
_, err = vl.lvmctrld.LvChange(ctx, &pb.LvChangeRequest{
Target: []string{vol.VgLv()},
Activate: pb.LvActivationMode_LV_ACTIVATION_MODE_DEACTIVATE,
})
if err != nil {
klog.Warningf("Failed to unlock volume %q: %v", *vol, err)
}
// Try to remove owner tag. We could race here and have another host lock the
// volume. In such case, the update will fail with permission denied.
err := vl.setOwner(ctx, *vol, nil, nil)
if err != nil && status.Code(err) != codes.PermissionDenied {
klog.Warningf("failed to update tags on volume %q: %v", *vol, err)
}
continue
}
// The volume is not locked, take note
vl.locks[vol.VgLv()] = map[string]struct{}{defaultLockOp: {}}
}
return nil
}