-
Notifications
You must be signed in to change notification settings - Fork 99
/
Copy pathagent.go
570 lines (486 loc) · 15.5 KB
/
agent.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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
/*
Copyright © 2019 The OpenEBS Authors
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 driver
import (
"errors"
"net/http"
"os"
"strings"
"sync"
"github.com/prometheus/client_golang/prometheus"
"github.com/prometheus/client_golang/prometheus/collectors"
"github.com/prometheus/client_golang/prometheus/promhttp"
"github.com/openebs/lvm-localpv/pkg/collector"
"github.com/container-storage-interface/spec/lib/go/csi"
"github.com/openebs/lib-csi/pkg/btrfs"
k8sapi "github.com/openebs/lib-csi/pkg/client/k8s"
"github.com/openebs/lib-csi/pkg/mount"
"golang.org/x/net/context"
"golang.org/x/sys/unix"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/klog/v2"
apis "github.com/openebs/lvm-localpv/pkg/apis/openebs.io/lvm/v1alpha1"
"github.com/openebs/lvm-localpv/pkg/builder/volbuilder"
"github.com/openebs/lvm-localpv/pkg/lvm"
"github.com/openebs/lvm-localpv/pkg/mgmt/lvmnode"
"github.com/openebs/lvm-localpv/pkg/mgmt/snapshot"
"github.com/openebs/lvm-localpv/pkg/mgmt/volume"
"sigs.k8s.io/controller-runtime/pkg/manager/signals"
)
// node is the server implementation
// for CSI NodeServer
type node struct {
driver *CSIDriver
}
// NewNode returns a new instance
// of CSI NodeServer
func NewNode(d *CSIDriver) csi.NodeServer {
var ControllerMutex = sync.RWMutex{}
// set up signals so we handle the first shutdown signal gracefully
stopCh := signals.SetupSignalHandler()
// start the lvm node resource watcher
go func() {
err := lvmnode.Start(&ControllerMutex, stopCh, d.config.NodeControllerPollingInterval)
if err != nil {
klog.Fatalf("Failed to start LVM node controller: %s", err.Error())
}
}()
// start the lvmvolume watcher
go func() {
err := volume.Start(&ControllerMutex, stopCh)
if err != nil {
klog.Fatalf("Failed to start LVM volume management controller: %s", err.Error())
}
}()
// start the lvm snapshot watcher
go func() {
err := snapshot.Start(&ControllerMutex, stopCh)
if err != nil {
klog.Fatalf("Failed to start LVM volume snapshot management controller: %s", err.Error())
}
}()
if d.config.ListenAddress != "" {
exposeMetrics(d.config.ListenAddress, d.config.MetricsPath, d.config.DisableExporterMetrics)
}
return &node{
driver: d,
}
}
// Function to register collectors to collect LVM related metrics and exporter metrics.
//
// If disableExporterMetrics is set to false, exporter will include metrics about itself i.e (process_*, go_*).
func registerCollectors(disableExporterMetrics bool) (*prometheus.Registry, error) {
registry := prometheus.NewRegistry()
if !disableExporterMetrics {
processCollector := collectors.NewProcessCollector(collectors.ProcessCollectorOpts{})
err := registry.Register(processCollector)
if err != nil {
klog.Errorf("failed to register process collector for exporter metrics collection: %s", err.Error())
return nil, err
}
goProcessCollector := collectors.NewGoCollector()
err = registry.Register(goProcessCollector)
if err != nil {
klog.Errorf("failed to register go process collector for exporter metrics collection: %s", err.Error())
return nil, err
}
}
lvmVgCollector := collector.NewVgCollector()
err := registry.Register(lvmVgCollector)
if err != nil {
klog.Errorf("failed to register LVM VG collector for LVM metrics collection: %s", err.Error())
return nil, err
}
lvmLvCollector := collector.NewLvCollector()
err = registry.Register(lvmLvCollector)
if err != nil {
klog.Errorf("failed to register LVM LV collector for LVM metrics collection: %s", err.Error())
return nil, err
}
lvmPvCollector := collector.NewPvCollector()
err = registry.Register(lvmPvCollector)
if err != nil {
klog.Errorf("failed to register LVM PV collector for LVM metrics collection: %s", err.Error())
return nil, err
}
return registry, nil
}
type promLog struct{}
// Implementation of Println(...) method of Logger interface of prometheus client_go.
func (p *promLog) Println(v ...interface{}) {
klog.Error(v...)
}
func promLogger() *promLog {
return &promLog{}
}
// Function to start HTTP server to expose LVM metrics.
//
// Parameters:
//
// listenAddr: TCP network address where the prometheus metrics endpoint will listen.
//
// metricsPath: The HTTP path where prometheus metrics will be exposed.
//
// disableExporterMetrics: Exclude metrics about the exporter itself (process_*, go_*).
func exposeMetrics(listenAddr string, metricsPath string, disableExporterMetrics bool) {
// Registry with all the collectors registered
registry, err := registerCollectors(disableExporterMetrics)
if err != nil {
klog.Fatalf("Failed to register collectors for LVM metrics collection: %s", err.Error())
}
http.Handle(metricsPath, promhttp.InstrumentMetricHandler(registry, promhttp.HandlerFor(registry, promhttp.HandlerOpts{
ErrorLog: promLogger(),
})))
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(`<html>
<head><title>LVM Exporter</title></head>
<body>
<h1>LVM Exporter</h1>
<p><a href="` + metricsPath + `">Metrics</a></p>
</body>
</html>`))
})
go func() {
if err := http.ListenAndServe(listenAddr, nil); err != nil {
klog.Fatalf("Failed to start HTTP server at specified address (%q) and metrics path (%q) to expose LVM metrics: %s", listenAddr, metricsPath, err.Error())
}
}()
}
// GetVolAndMountInfo get volume and mount info from node csi volume request
func GetVolAndMountInfo(
req *csi.NodePublishVolumeRequest,
) (*apis.LVMVolume, *lvm.MountInfo, error) {
var mountinfo lvm.MountInfo
mountinfo.FSType = req.GetVolumeCapability().GetMount().GetFsType()
mountinfo.MountPath = req.GetTargetPath()
mountinfo.MountOptions = append(mountinfo.MountOptions, req.GetVolumeCapability().GetMount().GetMountFlags()...)
if req.GetReadonly() {
mountinfo.MountOptions = append(mountinfo.MountOptions, "ro")
}
volName := strings.ToLower(req.GetVolumeId())
getOptions := metav1.GetOptions{}
vol, err := volbuilder.NewKubeclient().
WithNamespace(lvm.LvmNamespace).
Get(volName, getOptions)
if err != nil {
return nil, nil, err
}
return vol, &mountinfo, nil
}
func getPodLVInfo(req *csi.NodePublishVolumeRequest) (*lvm.PodLVInfo, error) {
var podLVInfo lvm.PodLVInfo
var ok bool
if podLVInfo.UID, ok = req.VolumeContext["csi.storage.k8s.io/pod.uid"]; !ok {
return nil, errors.New("csi.storage.k8s.io/pod.uid key missing in VolumeContext")
}
if podLVInfo.LVGroup, ok = req.VolumeContext["openebs.io/volgroup"]; !ok {
return nil, errors.New("openebs.io/volgroup key missing in VolumeContext")
}
return &podLVInfo, nil
}
// NodePublishVolume publishes (mounts) the volume
// at the corresponding node at a given path
//
// This implements csi.NodeServer
func (ns *node) NodePublishVolume(
ctx context.Context,
req *csi.NodePublishVolumeRequest,
) (*csi.NodePublishVolumeResponse, error) {
var (
err error
)
if err = ns.validateNodePublishReq(req); err != nil {
return nil, err
}
vol, mountInfo, err := GetVolAndMountInfo(req)
if err != nil {
return nil, status.Error(codes.Internal, err.Error())
}
podLVinfo, err := getPodLVInfo(req)
if err != nil {
klog.Warningf("PodLVInfo could not be obtained for volume_id: %s, err = %v", req.VolumeId, err)
}
switch req.GetVolumeCapability().GetAccessType().(type) {
case *csi.VolumeCapability_Block:
// attempt block mount operation on the requested path
err = lvm.MountBlock(vol, mountInfo, podLVinfo)
case *csi.VolumeCapability_Mount:
// attempt filesystem mount operation on the requested path
err = lvm.MountFilesystem(vol, mountInfo, podLVinfo)
}
if err != nil {
return nil, err
}
return &csi.NodePublishVolumeResponse{}, nil
}
// NodeUnpublishVolume unpublishes (unmounts) the volume
// from the corresponding node from the given path
//
// This implements csi.NodeServer
func (ns *node) NodeUnpublishVolume(
ctx context.Context,
req *csi.NodeUnpublishVolumeRequest,
) (*csi.NodeUnpublishVolumeResponse, error) {
var (
err error
vol *apis.LVMVolume
)
if err = ns.validateNodeUnpublishReq(req); err != nil {
return nil, err
}
targetPath := req.GetTargetPath()
volumeID := req.GetVolumeId()
if vol, err = lvm.GetLVMVolume(volumeID); err != nil {
return nil, status.Errorf(codes.Internal,
"not able to get the LVMVolume %s err : %s",
volumeID, err.Error())
}
err = lvm.UmountVolume(vol, targetPath)
if err != nil {
return nil, status.Errorf(codes.Internal,
"unable to umount the volume %s err : %s",
volumeID, err.Error())
}
klog.Infof("hostpath: volume %s path: %s has been unmounted.",
volumeID, targetPath)
return &csi.NodeUnpublishVolumeResponse{}, nil
}
// NodeGetInfo returns node details
//
// This implements csi.NodeServer
func (ns *node) NodeGetInfo(
ctx context.Context,
req *csi.NodeGetInfoRequest,
) (*csi.NodeGetInfoResponse, error) {
node, err := k8sapi.GetNode(ns.driver.config.NodeID)
if err != nil {
klog.Errorf("failed to get the node %s", ns.driver.config.NodeID)
return nil, err
}
/*
* The driver will support all the keys and values defined in the node's label.
* if nodes are labeled with the below keys and values
* map[beta.kubernetes.io/arch:amd64 beta.kubernetes.io/os:linux kubernetes.io/arch:amd64 kubernetes.io/hostname:pawan-node-1 kubernetes.io/os:linux node-role.kubernetes.io/worker:true openebs.io/zone:zone1 openebs.io/zpool:ssd]
* The driver will support below key and values
* {
* beta.kubernetes.io/arch:amd64
* beta.kubernetes.io/os:linux
* kubernetes.io/arch:amd64
* kubernetes.io/hostname:pawan-node-1
* kubernetes.io/os:linux
* node-role.kubernetes.io/worker:true
* openebs.io/zone:zone1
* openebs.io/zpool:ssd
* }
*/
// add driver's topology key
topology := map[string]string{
lvm.LVMTopologyKey: ns.driver.config.NodeID,
}
// support topologykeys from env ALLOWED_TOPOLOGIES
allowedTopologies := os.Getenv("ALLOWED_TOPOLOGIES")
allowedKeys := strings.Split(allowedTopologies, ",")
for _, key := range allowedKeys {
if key != "" {
v, ok := node.Labels[key]
if ok {
topology[key] = v
}
}
}
return &csi.NodeGetInfoResponse{
NodeId: ns.driver.config.NodeID,
AccessibleTopology: &csi.Topology{
Segments: topology,
},
}, nil
}
// NodeGetCapabilities returns capabilities supported
// by this node service
//
// This implements csi.NodeServer
func (ns *node) NodeGetCapabilities(
ctx context.Context,
req *csi.NodeGetCapabilitiesRequest,
) (*csi.NodeGetCapabilitiesResponse, error) {
return &csi.NodeGetCapabilitiesResponse{
Capabilities: []*csi.NodeServiceCapability{
{
Type: &csi.NodeServiceCapability_Rpc{
Rpc: &csi.NodeServiceCapability_RPC{
Type: csi.NodeServiceCapability_RPC_GET_VOLUME_STATS,
},
},
},
{
Type: &csi.NodeServiceCapability_Rpc{
Rpc: &csi.NodeServiceCapability_RPC{
Type: csi.NodeServiceCapability_RPC_EXPAND_VOLUME,
},
},
},
},
}, nil
}
// TODO
// This needs to be implemented
//
// NodeStageVolume mounts the volume on the staging
// path
//
// This implements csi.NodeServer
func (ns *node) NodeStageVolume(
ctx context.Context,
req *csi.NodeStageVolumeRequest,
) (*csi.NodeStageVolumeResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
// NodeUnstageVolume unmounts the volume from
// the staging path
//
// This implements csi.NodeServer
func (ns *node) NodeUnstageVolume(
ctx context.Context,
req *csi.NodeUnstageVolumeRequest,
) (*csi.NodeUnstageVolumeResponse, error) {
return nil, status.Error(codes.Unimplemented, "")
}
// TODO
// Verify if this needs to be implemented
//
// # NodeExpandVolume resizes the filesystem if required
//
// If ControllerExpandVolumeResponse returns true in
// node_expansion_required then FileSystemResizePending
// condition will be added to PVC and NodeExpandVolume
// operation will be queued on kubelet
//
// This implements csi.NodeServer
func (ns *node) NodeExpandVolume(
ctx context.Context,
req *csi.NodeExpandVolumeRequest,
) (*csi.NodeExpandVolumeResponse, error) {
volumeID := req.GetVolumeId()
if req.GetVolumePath() == "" || volumeID == "" {
return nil, status.Errorf(
codes.InvalidArgument,
"path not provided for NodeExpandVolume Request %s",
volumeID,
)
}
vol, err := lvm.GetLVMVolume(volumeID)
if err != nil {
return nil, status.Errorf(
codes.NotFound,
"failed to handle NodeExpandVolume Request for %s, {%s}",
req.VolumeId,
err.Error(),
)
}
isBlockMode := req.GetVolumeCapability().GetBlock() != nil
fsType := req.GetVolumeCapability().GetMount().GetFsType()
resizeFS := true
if isBlockMode || fsType == "btrfs" {
// In case of volume block mode (or) btrfs filesystem mode
// lvm doesn't expand the fs natively
resizeFS = false
}
err = lvm.ResizeLVMVolume(vol, resizeFS)
if err != nil {
return nil, status.Errorf(
codes.Internal,
"failed to handle NodeExpandVolume Request for %s, {%s}",
req.VolumeId,
err.Error(),
)
}
// Expand btrfs filesystem
if fsType == "btrfs" {
err = btrfs.ResizeBTRFS(req.GetVolumePath())
if err != nil {
return nil, status.Errorf(
codes.Internal,
"failed to handle NodeExpandVolume Request for %s, {%s}",
req.VolumeId,
err.Error(),
)
}
}
return &csi.NodeExpandVolumeResponse{
CapacityBytes: req.GetCapacityRange().GetRequiredBytes(),
}, nil
}
// NodeGetVolumeStats returns statistics for the
// given volume
func (ns *node) NodeGetVolumeStats(
ctx context.Context,
req *csi.NodeGetVolumeStatsRequest,
) (*csi.NodeGetVolumeStatsResponse, error) {
volID := req.GetVolumeId()
path := req.GetVolumePath()
if len(volID) == 0 {
return nil, status.Error(codes.InvalidArgument, "volume id is not provided")
}
if len(path) == 0 {
return nil, status.Error(codes.InvalidArgument, "path is not provided")
}
if !mount.IsMountPath(path) {
return nil, status.Error(codes.NotFound, "path is not a mount path")
}
var sfs unix.Statfs_t
if err := unix.Statfs(path, &sfs); err != nil {
return nil, status.Errorf(codes.Internal, "statfs on %s failed: %v", path, err)
}
var usage []*csi.VolumeUsage
usage = append(usage, &csi.VolumeUsage{
Unit: csi.VolumeUsage_BYTES,
Total: int64(sfs.Blocks) * int64(sfs.Bsize),
Used: int64(sfs.Blocks-sfs.Bfree) * int64(sfs.Bsize),
Available: int64(sfs.Bavail) * int64(sfs.Bsize),
})
usage = append(usage, &csi.VolumeUsage{
Unit: csi.VolumeUsage_INODES,
Total: int64(sfs.Files),
Used: int64(sfs.Files - sfs.Ffree),
Available: int64(sfs.Ffree),
})
return &csi.NodeGetVolumeStatsResponse{Usage: usage}, nil
}
func (ns *node) validateNodePublishReq(
req *csi.NodePublishVolumeRequest,
) error {
if req.GetVolumeCapability() == nil {
return status.Error(codes.InvalidArgument,
"Volume capability missing in request")
}
if len(req.GetVolumeId()) == 0 {
return status.Error(codes.InvalidArgument,
"Volume ID missing in request")
}
return nil
}
func (ns *node) validateNodeUnpublishReq(
req *csi.NodeUnpublishVolumeRequest,
) error {
if req.GetVolumeId() == "" {
return status.Error(codes.InvalidArgument,
"Volume ID missing in request")
}
if req.GetTargetPath() == "" {
return status.Error(codes.InvalidArgument,
"Target path missing in request")
}
return nil
}