从emptyDir到CSI gRPC接口的三个Identity/Controller/Node Service,再到Volume Attach/Mount的完整kubelet调用链与自定义CSI驱动开发——本章把K8s存储体系拆到gRPC方法签名和内核mount系统调用层面。
K8s的存储体系经历了三代演进:in-tree Volume插件 → FlexVolume → CSI(Container Storage Interface)。理解这个演进过程是理解当前存储架构的前提。
| 维度 | in-tree Volume | FlexVolume | CSI |
|---|---|---|---|
| 实现位置 | k8s源码树内 | 节点上的脚本/binary | 独立容器化组件 |
| 接口协议 | Go接口 | JSON+命令行 | gRPC (protobuf) |
| 生命周期 | 绑定k8s版本 | 节点部署 | 独立发布 |
| 可扩展性 | 需改k8s源码 | 放脚本即可 | 标准CSI spec |
| 跨平台 | 是 | 弱(依赖bash) | 是(gRPC跨语言) |
| 当前状态 | 迁移到CSI (1.26+) | 已废弃 | 唯一推荐方式 |
| 类别 | 类型 | 生命周期 | 典型用途 |
|---|---|---|---|
| 临时存储 | emptyDir | Pod删除时清除 | 缓存、临时文件 |
| 临时存储 | configMap/secret/downwardAPI | Pod删除时清除 | 配置注入 |
| 节点本地 | hostPath | 持久(节点级) | daemonset访问节点文件 |
| 节点本地 | local | 持久(节点级) | 高性能本地存储 |
| 网络存储 | nfs/iscsi/cephfs/glusterfs | 持久 | 共享文件系统 |
| 块存储 | PV (CSI) | 持久 | 数据库、有状态应用 |
| 投射 | projected | Pod删除时清除 | 多源配置合并 |
| CSI ephemeral | csi (ephemeral mode) | Pod删除时清除 | 临时CSI卷 |
StorageClass (存储类) PV (物理卷)
│ provisioner: csi-driver │ capacity: 100Gi
│ parameters: {type: ssd} │ accessModes: [RWO]
│ reclaimPolicy: Delete │ storageClassName: fast-ssd
│ │ csi:
│ ┌─────────────────────────────┤ driver: disk.csi.example.com
│ │ 动态provision │ volumeHandle: vol-abc123
│ ▼ │
PVC (声明) │
│ spec: │
│ storageClassName: fast-ssd │
│ accessModes: [RWO] │
│ resources: │
│ requests: {storage: 100Gi} │
│ ─────────────────────────────►│ bound
│ status: phase: Bound │
▼ ▼
Pod (消费者)
spec.volumes:
- name: data
persistentVolumeClaim:
claimName: my-pvc
StorageClass是"菜单"(告诉系统你要什么规格的存储),PVC是"订单"(我要一份100G的SSD),PV是"实际做出来的菜"(一块真实的100G磁盘)。静态provision是你自己做好菜(手动创建PV)让订单匹配;动态provision是系统看到订单后自动做菜(CSI driver创建磁盘)。
CSI(Container Storage Interface)是K8s/Containerd/Mesos等容器编排系统共同遵循的存储接口标准。规范定义在container-storage-interface/spec,当前版本1.9.0。
┌─────────────────────────────────────────────────┐
│ Kubernetes控制面 │
│ ┌──────────┐ ┌──────────────┐ ┌────────────┐ │
│ │ API Server│ │ CSI Driver │ │ CSI Driver │ │
│ │ │ │ Controller │ │ Node │ │
│ │ │ │ (StatefulSet)│ │ (DaemonSet) │ │
│ └──────────┘ └──────┬───────┘ └─────┬──────┘ │
│ │ │ │
│ ┌────────────────────┴─────────────────┴──────┐ │
│ │ external-provisioner external-attacher │ │
│ │ external-snapshotter external-resizer │ │
│ │ external-health-monitor node-driver-registrar│ │
│ └─────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────┘
│ gRPC (Unix Domain Socket)
▼
┌────────────────┐
│ CSI Driver │
│ (Storage后端) │
└────────────────┘
CSI规范定义了三个gRPC Service,每个驱动必须实现:
驱动身份标识。所有组件(controller和node)都需实现。
卷的控制面操作(创建/删除/attach/snapshot/扩容)。通常以StatefulSet运行,单实例。
节点上的卷操作(mount/umount/格式化)。以DaemonSet运行,每节点一个实例。
// Identity Service
service Identity {
rpc GetPluginInfo(GetPluginInfoRequest)
returns (GetPluginInfoResponse) {}
rpc GetPluginCapabilities(GetPluginCapabilitiesRequest)
returns (GetPluginCapabilitiesResponse) {}
rpc Probe(ProbeRequest) returns (ProbeResponse) {}
}
// Controller Service
service Controller {
rpc CreateVolume(CreateVolumeRequest)
returns (CreateVolumeResponse) {}
rpc DeleteVolume(DeleteVolumeRequest)
returns (DeleteVolumeResponse) {}
rpc ControllerPublishVolume(ControllerPublishVolumeRequest)
returns (ControllerPublishVolumeResponse) {}
rpc ControllerUnpublishVolume(ControllerUnpublishVolumeRequest)
returns (ControllerUnpublishVolumeResponse) {}
rpc ValidateVolumeCapabilities(ValidateVolumeCapabilitiesRequest)
returns (ValidateVolumeCapabilitiesResponse) {}
rpc ListVolumes(ListVolumesRequest)
returns (ListVolumesResponse) {}
rpc ControllerGetCapabilities(ControllerGetCapabilitiesRequest)
returns (ControllerGetCapabilitiesResponse) {}
rpc CreateSnapshot(CreateSnapshotRequest)
returns (CreateSnapshotResponse) {}
rpc DeleteSnapshot(DeleteSnapshotRequest)
returns (DeleteSnapshotResponse) {}
rpc ControllerExpandVolume(ControllerExpandVolumeRequest)
returns (ControllerExpandVolumeResponse) {}
rpc GetCapacity(GetCapacityRequest)
returns (GetCapacityResponse) {}
}
// Node Service
service Node {
rpc NodeStageVolume(NodeStageVolumeRequest)
returns (NodeStageVolumeResponse) {}
rpc NodeUnstageVolume(NodeUnstageVolumeRequest)
returns (NodeUnstageVolumeResponse) {}
rpc NodePublishVolume(NodePublishVolumeRequest)
returns (NodePublishVolumeResponse) {}
rpc NodeUnpublishVolume(NodeUnpublishVolumeRequest)
returns (NodeUnpublishVolumeResponse) {}
rpc NodeGetCapabilities(NodeGetCapabilitiesRequest)
returns (NodeGetCapabilitiesResponse) {}
rpc NodeGetInfo(NodeGetInfoRequest)
returns (NodeGetInfoResponse) {}
rpc NodeExpandVolume(NodeExpandVolumeRequest)
returns (NodeExpandVolumeResponse) {}
}
一个动态provisioned CSI卷的完整生命周期:
[1] 创建PVC
└─ external-provisioner watch到PVC
└─ CreateVolume(capacity=100Gi, name=vol-xxx)
└─ CSI驱动在后端存储创建100Gi卷
└─ 返回volume_id
└─ 创建PV (csi.volumeHandle=vol-xxx)
└─ PVC bound to PV
[2] Pod调度到Node-A
└─ kubelet watch到Pod
└─ VolumeManager开始attach
└─ external-attacher watch到VolumeAttachment
└─ ControllerPublishVolume(volume_id, node_id)
└─ CSI驱动将卷attach到Node-A
└─ 返回device_path (/dev/sdb)
[3] kubelet mount卷
└─ NodeStageVolume(volume_id, staging_path, device_path)
└─ CSI驱动格式化/dev/sdb → ext4
└─ mount /dev/sdb → /var/lib/kubelet/staging/vol-xxx
└─ NodePublishVolume(volume_id, staging_path, target_path)
└─ bind mount staging_path → target_path
(即Pod内的mount point)
[4] Pod删除
└─ NodeUnpublishVolume(volume_id, target_path)
└─ umount target_path
└─ NodeUnstageVolume(volume_id, staging_path)
└─ umount staging_path
└─ ControllerUnpublishVolume(volume_id, node_id)
└─ 从Node-A detach卷
└─ 如果reclaimPolicy=Delete:
└─ DeleteVolume(volume_id)
└─ 删除后端存储卷
NodeStageVolume将块设备格式化并mount到staging path(/var/lib/kubelet/plugins/csi-driver/staging/),这是节点级的一次性操作。NodePublishVolume将staging path bind mount到每个Pod的target path。这样设计是为了:同一个卷被同节点多个Pod使用时,只需Stage一次(格式化+mount),每个Pod只需轻量的bind mount。这就是为什么有"staging"和"publish"两步。
本节开发一个最小可用的CSI驱动——nfs-csi-simple,它在后端用NFS server提供存储。
nfs-csi-simple/
├── cmd/
│ ├── main.go # 入口
│ └── driver/
│ ├── driver.go # 驱动主结构
│ ├── identity.go # Identity Service实现
│ ├── controller.go # Controller Service实现
│ └── node.go # Node Service实现
├── deploy/
│ ├── controller.yaml # Controller组件部署
│ ├── node.yaml # Node组件DaemonSet
│ └── storageclass.yaml # StorageClass
├── pkg/
│ └── nfs/
│ └── client.go # NFS后端操作
├── go.mod
└── Dockerfile
package driver
import (
"context"
"github.com/container-storage-interface/spec/lib/go/csi"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type IdentityServer struct {
name string
version string
}
func NewIdentityServer(name, version string) *IdentityServer {
return &IdentityServer{name: name, version: version}
}
func (s *IdentityServer) GetPluginInfo(
ctx context.Context, req *csi.GetPluginInfoRequest,
) (*csi.GetPluginInfoResponse, error) {
if s.name == "" {
return nil, status.Error(codes.Unavailable, "driver name not set")
}
return &csi.GetPluginInfoResponse{
Name: s.name, // 如 "nfs.csi.simple.example.com"
VendorVersion: s.version, // 如 "v1.0.0"
}, nil
}
func (s *IdentityServer) GetPluginCapabilities(
ctx context.Context, req *csi.GetPluginCapabilitiesRequest,
) (*csi.GetPluginCapabilitiesResponse, error) {
return &csi.GetPluginCapabilitiesResponse{
Capabilities: []*csi.PluginCapability{
{
Type: &csi.PluginCapability_Service_{
Service: &csi.PluginCapability_Service{
Type: csi.PluginCapability_Service_CONTROLLER_SERVICE,
},
},
},
{
Type: &csi.PluginCapability_VolumeExpansion_{
VolumeExpansion: &csi.PluginCapability_VolumeExpansion{
Type: csi.PluginCapability_VolumeExpansion_ONLINE,
},
},
},
},
}, nil
}
func (s *IdentityServer) Probe(
ctx context.Context, req *csi.ProbeRequest,
) (*csi.ProbeResponse, error) {
// 健康检查:验证NFS server可达
// 这里简化为总是返回OK
return &csi.ProbeResponse{
Ready: &csi.ProbeResponse_Ready{Value: true},
}, nil
}
package driver
import (
"context"
"fmt"
"strconv"
"github.com/container-storage-interface/spec/lib/go/csi"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type ControllerServer struct {
nfsClient *nfs.Client
caps []*csi.ControllerServiceCapability
}
func (s *ControllerServer) CreateVolume(
ctx context.Context, req *csi.CreateVolumeRequest,
) (*csi.CreateVolumeResponse, error) {
// 1. 参数校验
if req.Name == "" {
return nil, status.Error(codes.InvalidArgument, "volume name required")
}
if req.CapacityRange == nil {
return nil, status.Error(codes.InvalidArgument, "capacity range required")
}
// 2. 计算所需容量
requiredBytes := req.CapacityRange.GetRequiredBytes()
limitBytes := req.CapacityRange.GetLimitBytes()
if limitBytes > 0 && requiredBytes > limitBytes {
return nil, status.Error(codes.OutOfRange, "required > limit")
}
// 3. 从Secrets获取NFS server信息
nfsServer := req.Secrets["nfsServer"]
nfsPath := req.Secrets["nfsPath"]
// 4. 从参数获取存储参数
// StorageClass的parameters会传到这里
shareName := req.Parameters["shareName"]
if shareName == "" {
shareName = req.Name // 默认用volume name
}
// 5. 在NFS server上创建子目录(作为卷)
volumeID := fmt.Sprintf("%s/%s/%s", nfsServer, nfsPath, shareName)
err := s.nfsClient.CreateShare(ctx, nfsServer, nfsPath, shareName, requiredBytes)
if err != nil {
return nil, status.Errorf(codes.Internal,
"failed to create share %s: %v", shareName, err)
}
// 6. 返回创建的卷信息
return &csi.CreateVolumeResponse{
Volume: &csi.Volume{
VolumeId: volumeID,
CapacityBytes: requiredBytes,
VolumeContext: map[string]string{
"server": nfsServer,
"share": nfsPath + "/" + shareName,
},
// 声明此卷的访问能力
AccessibleTopology: nil, // 不限制拓扑
},
}, nil
}
func (s *ControllerServer) DeleteVolume(
ctx context.Context, req *csi.DeleteVolumeRequest,
) (*csi.DeleteVolumeResponse, error) {
if req.VolumeId == "" {
return nil, status.Error(codes.InvalidArgument, "volume ID required")
}
// 解析volume ID: server/path/share
err := s.nfsClient.DeleteShare(ctx, req.VolumeId)
if err != nil {
return nil, status.Errorf(codes.Internal,
"failed to delete volume %s: %v", req.VolumeId, err)
}
return &csi.DeleteVolumeResponse{}, nil
}
func (s *ControllerServer) ControllerPublishVolume(
ctx context.Context, req *csi.ControllerPublishVolumeRequest,
) (*csi.ControllerPublishVolumeResponse, error) {
// NFS不需要attach操作(网络文件系统无块设备attach)
// 直接返回成功
return &csi.ControllerPublishVolumeResponse{
PublishContext: req.VolumeContext,
}, nil
}
func (s *ControllerServer) ControllerUnpublishVolume(
ctx context.Context, req *csi.ControllerUnpublishVolumeRequest,
) (*csi.ControllerUnpublishVolumeResponse, error) {
// NFS不需要detach操作
return &csi.ControllerUnpublishVolumeResponse{}, nil
}
func (s *ControllerServer) ControllerGetCapabilities(
ctx context.Context, req *csi.ControllerGetCapabilitiesRequest,
) (*csi.ControllerGetCapabilitiesResponse, error) {
return &csi.ControllerGetCapabilitiesResponse{
Capabilities: s.caps,
}, nil
}
// 在构造函数中声明能力
func NewControllerServer(nfs *nfs.Client) *ControllerServer {
caps := []*csi.ControllerServiceCapability{
// 支持创建/删除卷
cap(csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME),
// 支持publish/unpublish(即使NFS是no-op也要声明)
cap(csi.ControllerServiceCapability_RPC_PUBLISH_UNPUBLISH_VOLUME),
// 支持扩容
cap(csi.ControllerServiceCapability_RPC_EXPAND_VOLUME),
// 支持快照
cap(csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT),
}
return &ControllerServer{nfsClient: nfs, caps: caps}
}
package driver
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"github.com/container-storage-interface/spec/lib/go/csi"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type NodeServer struct {
nodeID string
caps []*csi.NodeServiceCapability
}
func (s *NodeServer) NodeStageVolume(
ctx context.Context, req *csi.NodeStageVolumeRequest,
) (*csi.NodeStageVolumeResponse, error) {
// 1. 校验参数
if req.VolumeId == "" {
return nil, status.Error(codes.InvalidArgument, "volume ID required")
}
if req.StagingTargetPath == "" {
return nil, status.Error(codes.InvalidArgument, "staging path required")
}
// 2. 从volume context获取NFS server和share
server := req.VolumeContext["server"]
share := req.VolumeContext["share"]
// 3. 确保staging目录存在
if err := os.MkdirAll(req.StagingTargetPath, 0755); err != nil {
return nil, status.Errorf(codes.Internal,
"mkdir staging path failed: %v", err)
}
// 4. 检查是否已mount(幂等性)
if isMounted, _ := checkMount(req.StagingTargetPath); isMounted {
return &csi.NodeStageVolumeResponse{}, nil // 已mount,直接返回
}
// 5. 执行NFS mount
nfsSource := fmt.Sprintf("%s:/%s", server, share)
cmd := exec.Command("mount", "-t", "nfs", "-o", "nfsvers=4.1",
nfsSource, req.StagingTargetPath)
if err := cmd.Run(); err != nil {
return nil, status.Errorf(codes.Internal,
"nfs mount failed: %v (cmd: %s)", err, cmd.String())
}
return &csi.NodeStageVolumeResponse{}, nil
}
func (s *NodeServer) NodePublishVolume(
ctx context.Context, req *csi.NodePublishVolumeRequest,
) (*csi.NodePublishVolumeResponse, error) {
// 1. 校验
if req.VolumeId == "" {
return nil, status.Error(codes.InvalidArgument, "volume ID required")
}
if req.TargetPath == "" {
return nil, status.Error(codes.InvalidArgument, "target path required")
}
if req.StagingSourcePath == "" {
return nil, status.Error(codes.InvalidArgument, "staging source required")
}
// 2. 创建target目录
if err := os.MkdirAll(req.TargetPath, 0755); err != nil {
return nil, status.Errorf(codes.Internal, "mkdir target: %v", err)
}
// 3. 检查是否已bind mount
if isMounted, _ := checkMount(req.TargetPath); isMounted {
return &csi.NodePublishVolumeResponse{}, nil
}
// 4. bind mount: staging → target
mountFlags := []string{"bind"}
if req.Readonly {
mountFlags = append(mountFlags, "ro")
}
cmd := exec.Command("mount", "-o", strings.Join(mountFlags, ","),
req.StagingSourcePath, req.TargetPath)
if err := cmd.Run(); err != nil {
return nil, status.Errorf(codes.Internal, "bind mount failed: %v", err)
}
return &csi.NodePublishVolumeResponse{}, nil
}
func (s *NodeServer) NodeUnpublishVolume(
ctx context.Context, req *csi.NodeUnpublishVolumeRequest,
) (*csi.NodeUnpublishVolumeResponse, error) {
if req.TargetPath == "" {
return nil, status.Error(codes.InvalidArgument, "target path required")
}
// umount target path
cmd := exec.Command("umount", req.TargetPath)
if err := cmd.Run(); err != nil {
// 如果已经umount了,忽略错误(幂等性)
if !isNotMounted(err) {
return nil, status.Errorf(codes.Internal, "umount failed: %v", err)
}
}
// 清理目录
os.Remove(req.TargetPath)
return &csi.NodeUnpublishVolumeResponse{}, nil
}
func (s *NodeServer) NodeUnstageVolume(
ctx context.Context, req *csi.NodeUnstageVolumeRequest,
) (*csi.NodeUnstageVolumeResponse, error) {
if req.StagingTargetPath == "" {
return nil, status.Error(codes.InvalidArgument, "staging path required")
}
// umount NFS
cmd := exec.Command("umount", req.StagingTargetPath)
if err := cmd.Run(); err != nil {
if !isNotMounted(err) {
return nil, status.Errorf(codes.Internal, "umount staging: %v", err)
}
}
os.Remove(req.StagingTargetPath)
return &csi.NodeUnstageVolumeResponse{}, nil
}
func (s *NodeServer) NodeExpandVolume(
ctx context.Context, req *csi.NodeExpandVolumeRequest,
) (*csi.NodeExpandVolumeResponse, error) {
// NFS在线扩容:NFS server端扩容后,client自动看到新大小
// 只需返回新的容量
return &csi.NodeExpandVolumeResponse{
CapacityBytes: req.CapacityRange.GetRequiredBytes(),
}, nil
}
func (s *NodeServer) NodeGetInfo(
ctx context.Context, req *csi.NodeGetInfoRequest,
) (*csi.NodeGetInfoResponse, error) {
return &csi.NodeGetInfoResponse{
NodeId: s.nodeID, // 通常是节点名或节点IP
// 声明拓扑限制(如有)
// AccessibleTopology: &csi.Topology{Segments: map[string]string{...}},
}, nil
}
// 辅助函数:检查路径是否已mount
func checkMount(path string) (bool, error) {
cmd := exec.Command("mountpoint", path)
err := cmd.Run()
return err == nil, nil // exit 0 = is mountpoint
}
package main
import (
"net"
"os"
"google.golang.org/grpc"
"github.com/container-storage-interface/spec/lib/go/csi"
)
func main() {
// 1. 解析命令行参数
endpoint := os.Getenv("CSI_ENDPOINT") // unix:///csi/csi.sock
driverName := "nfs.csi.simple.example.com"
nodeID := os.Getenv("NODE_ID")
mode := os.Getenv("MODE") // "controller" or "node"
// 2. 创建Unix Domain Socket
if err := os.MkdirAll(filepath.Dir(endpoint), 0755); err != nil {
panic(err)
}
// 移除旧socket
os.Remove(strings.TrimPrefix(endpoint, "unix://"))
listener, err := net.Listen("unix", strings.TrimPrefix(endpoint, "unix://"))
if err != nil {
panic(err)
}
// 3. 创建gRPC server
grpcServer := grpc.NewServer(
grpc.UnaryInterceptor(loggingInterceptor),
)
// 4. 注册CSI服务
identity := NewIdentityServer(driverName, "v1.0.0")
csi.RegisterIdentityServer(grpcServer, identity)
if mode == "controller" {
nfsClient := nfs.NewClient()
controller := NewControllerServer(nfsClient)
csi.RegisterControllerServer(grpcServer, controller)
}
if mode == "node" {
node := NewNodeServer(nodeID)
csi.RegisterNodeServer(grpcServer, node)
}
// 5. 启动gRPC server
log.Infof("Starting CSI driver %s in %s mode on %s", driverName, mode, endpoint)
if err := grpcServer.Serve(listener); err != nil {
panic(err)
}
}
CSI驱动本身只是gRPC server,还需要一组sidecar容器来桥接K8s API和CSI gRPC接口。
| 组件 | 运行位置 | 职责 |
|---|---|---|
| external-provisioner | Controller Pod | watch PVC,调CreateVolume/DeleteVolume |
| external-attacher | Controller Pod | watch VolumeAttachment,调ControllerPublish/Unpublish |
| external-snapshotter | Controller Pod | watch VolumeSnapshot,调CreateSnapshot/DeleteSnapshot |
| external-resizer | Controller Pod | watch PVC扩容请求,调ControllerExpandVolume |
| node-driver-registrar | Node Pod (DaemonSet) | 向kubelet注册CSI驱动(创建CSINode对象) |
| external-health-monitor | Controller/Node Pod | 监控卷健康状态,更新PV/PVC事件 |
| liveness-probe | Controller/Node Pod | 调Probe()做健康检查,更新CSI驱动健康状态 |
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: nfs-csi-controller
namespace: kube-system
spec:
serviceName: nfs-csi-controller
replicas: 1
selector:
matchLabels: {app: nfs-csi-controller}
template:
metadata:
labels: {app: nfs-csi-controller}
spec:
serviceAccount: nfs-csi-controller
containers:
# CSI驱动本身
- name: csi-driver
image: nfs-csi-simple:v1.0.0
env:
- name: CSI_ENDPOINT
value: unix:///csi/csi.sock
- name: MODE
value: controller
volumeMounts:
- name: socket-dir
mountPath: /csi
# external-provisioner
- name: csi-provisioner
image: registry.k8s.io/sig-storage/csi-provisioner:v4.0.0
args:
- --csi-address=/csi/csi.sock
- --leader-election
- --extra-create-metadata=true
volumeMounts:
- name: socket-dir
mountPath: /csi
# external-attacher
- name: csi-attacher
image: registry.k8s.io/sig-storage/csi-attacher:v4.4.0
args:
- --csi-address=/csi/csi.sock
- --leader-election
volumeMounts:
- name: socket-dir
mountPath: /csi
# external-resizer
- name: csi-resizer
image: registry.k8s.io/sig-storage/csi-resizer:v1.9.0
args:
- --csi-address=/csi/csi.sock
- --leader-election
volumeMounts:
- name: socket-dir
mountPath: /csi
# liveness-probe
- name: liveness-probe
image: registry.k8s.io/sig-storage/livenessprobe:v2.12.0
args:
- --csi-address=/csi/csi.sock
volumeMounts:
- name: socket-dir
mountPath: /csi
volumes:
- name: socket-dir
emptyDir: {}
apiVersion: apps/v1
kind: DaemonSet
metadata:
name: nfs-csi-node
namespace: kube-system
spec:
selector:
matchLabels: {app: nfs-csi-node}
template:
metadata:
labels: {app: nfs-csi-node}
spec:
serviceAccount: nfs-csi-node
containers:
# CSI驱动
- name: csi-driver
image: nfs-csi-simple:v1.0.0
securityContext:
privileged: true # 需要执行mount命令
env:
- name: CSI_ENDPOINT
value: unix:///csi/csi.sock
- name: MODE
value: node
- name: NODE_ID
valueFrom:
fieldRef:
fieldPath: spec.nodeName
volumeMounts:
- name: socket-dir
mountPath: /csi
- name: mountpoint-dir
mountPath: /var/lib/kubelet
mountPropagation: Bidirectional # 关键!让mount对kubelet可见
- name: plugin-dir
mountPath: /var/lib/kubelet/plugins
# node-driver-registrar
- name: node-driver-registrar
image: registry.k8s.io/sig-storage/csi-node-driver-registrar:v2.9.0
args:
- --csi-address=/csi/csi.sock
- --kubelet-registration-path=/var/lib/kubelet/plugins/nfs.csi.simple.example.com/csi.sock
volumeMounts:
- name: socket-dir
mountPath: /csi
- name: registration-dir
mountPath: /registration
volumes:
- name: socket-dir
hostPath:
path: /var/lib/kubelet/plugins/nfs.csi.simple.example.com
type: DirectoryOrCreate
- name: mountpoint-dir
hostPath:
path: /var/lib/kubelet
type: Directory
- name: plugin-dir
hostPath:
path: /var/lib/kubelet/plugins
type: Directory
- name: registration-dir
hostPath:
path: /var/lib/kubelet/plugins_registry
type: Directory
CSI Node Pod必须设置mountPropagation: Bidirectional。原因:CSI驱动在容器内执行mount命令,但这个mount默认只在容器的mount namespace中生效,kubelet和Pod看不到。Bidirectional propagation让容器内的mount传播到宿主机的mount namespace,这样kubelet才能在Pod的target path看到挂载的卷。这需要privileged: true或CAP_SYS_ADMIN能力。
StorageClass是用户与CSI驱动之间的参数传递桥梁。StorageClass的parameters字段会传递给CSI驱动的CreateVolume调用。
apiVersion: storage.k8s.io/v1
kind: StorageClass
metadata:
name: nfs-simple
provisioner: nfs.csi.simple.example.com # 必须与驱动GetPluginInfo返回的name一致
reclaimPolicy: Delete # 或 Retain
allowVolumeExpansion: true # 允许扩容
volumeBindingMode: WaitForFirstConsumer # 延迟绑定(等Pod调度后再决定拓扑)
parameters:
# 这些参数会传给CreateVolumeRequest.Parameters
shareName: "${pvc.metadata.namespace}-${pvc.metadata.name}"
nfsServer: "nfs.example.com"
nfsPath: "/exported"
mountOptions:
- nfsvers=4.1
- hard
- rsize=1048576
- wsize=1048576
| 来源 | 字段 | 传递到CSI方法 | 字段 |
|---|---|---|---|
| StorageClass | parameters | CreateVolume | req.Parameters |
| StorageClass | mountOptions | NodeStageVolume | req.VolumeCapability.MountVolume.MountFlags |
| StorageClass | reclaimPolicy | —(由provisioner处理) | — |
| PVC | resources.requests.storage | CreateVolume | req.CapacityRange.RequiredBytes |
| PVC | accessModes | CreateVolume | req.VolumeCapabilities |
| PVC | spec.dataSource (snapshot) | CreateVolume | req.VolumeContentSource |
| Secret | StorageClass.secret | CreateVolume | req.Secrets |
| VolumeContext | CreateVolume返回的 | NodeStageVolume | req.VolumeContext |
# 在集群中部署一个NFS server用于测试
kubectl apply -f - <# 构建镜像
cd nfs-csi-simple
docker build -t nfs-csi-simple:v1.0.0 .
# 如果用kind集群:
kind load docker-image nfs-csi-simple:v1.0.0
# 部署RBAC
kubectl apply -f deploy/rbac.yaml
# 部署Controller
kubectl apply -f deploy/controller.yaml
# 部署Node DaemonSet
kubectl apply -f deploy/node.yaml
# 部署StorageClass
kubectl apply -f deploy/storageclass.yaml
# 验证驱动注册
kubectl get csinode
# NAME DRIVERS
# node-1 nfs.csi.simple.example.com
# node-2 nfs.csi.simple.example.com
kubectl get csidriver
# NAME ATTACHREQUIRED PODINFOONMOUNT
# nfs.csi.simple.example.com false false
# 创建PVC
kubectl apply -f - < /data/test.txt && sleep 3600"]
volumeMounts:
- name: data
mountPath: /data
volumes:
- name: data
persistentVolumeClaim:
claimName: test-pvc
EOF
# 等待Pod运行
kubectl wait pod test-pod --for=condition=ready --timeout=30s
# 验证数据写入
kubectl exec test-pod -- cat /data/test.txt
# hello
# 扩容PVC
kubectl patch pvc test-pvc -p '{"spec":{"resources":{"requests":{"storage":"10Gi"}}}}'
# 等待扩容完成
kubectl wait pvc test-pvc --for=jsonpath='{.status.conditions[?(@.type=="FileSystemResizePending")].reason}'= --timeout=30s 2>/dev/null || true
# 验证
kubectl get pvc test-pvc
# NAME STATUS VOLUME CAPACITY ...
# test-pvc Bound pvc-xxx 10Gi ...
kubectl exec test-pod -- df -h /data
# Filesystem Size Used Available Use% Mounted on
# nfs-server:/shared/... 10G 24K 10G 1% /data
# 查看Controller Pod日志
kubectl -n kube-system logs -l app=nfs-csi-controller -c csi-driver --tail=30
# 预期日志:
# [INFO] CreateVolume called: name=pvc-xxx, capacity=5Gi
# [INFO] Created NFS share: nfs-server:/shared/default-test-pvc
# [INFO] CreateVolume response: volume_id=nfs-server/shared/default-test-pvc
# 查看Node Pod日志
kubectl -n kube-system logs -l app=nfs-csi-node -c csi-driver --tail=30
# 预期日志:
# [INFO] NodeStageVolume: vol=nfs-server/shared/default-test-pvc
# [INFO] NFS mount: nfs-server:/shared/default-test-pvc → /var/lib/kubelet/staging/xxx
# [INFO] NodePublishVolume: bind mount staging → target
PVC Pending
│
├─ kubectl get pvc → 查看Events
│ kubectl describe pvc X
│ ├─ "failed to provision volume" → CSI驱动CreateVolume失败
│ │ └─ 查external-provisioner日志 + CSI驱动日志
│ ├─ "no volume plugin matched" → provisioner名称不匹配
│ └─ "storageclass not found" → StorageClass不存在
│
├─ PVC Bound但Pod ContainerCreating
│ kubectl describe pod X
│ ├─ "failed to attach" → ControllerPublishVolume失败
│ │ └─ 查external-attacher日志 + CSI Controller日志
│ ├─ "failed to mount" → NodeStageVolume/NodePublishVolume失败
│ │ └─ 查CSI Node Pod日志 + 节点dmesg
│ └─ "volume not found" → PV被意外删除
│
├─ Pod Running但I/O错误
│ ├─ 存储后端不可达 → 查网络 + 存储后端状态
│ ├─ 磁盘满 → df -h 在Pod内检查
│ └─ 权限问题 → ls -l 检查挂载点权限
| 现象 | 可能根因 | 诊断命令 | 解决方案 |
|---|---|---|---|
| PVC一直Pending | StorageClass不存在或provisioner名不匹配 | kubectl get sc; kubectl describe pvc | 修正StorageClass配置 |
| PVC Pending + provisioner日志报错 | CreateVolume失败(后端容量不足、权限问题) | 查provisioner + CSI驱动日志 | 修复后端或参数 |
| Pod ContainerCreating (mount失败) | NodeStageVolume失败(NFS server不可达、目录不存在) | 查CSI Node Pod日志 | 检查存储后端连通性 |
| Pod ContainerCreating (attach超时) | ControllerPublishVolume超时(存储后端慢) | 查attacher日志 | 增加超时或修复后端 |
| 卷只读 (read-only filesystem) | 存储后端故障导致remount为ro | dmesg | grep -i "read-only" | 修复后端,重新挂载 |
| 扩容失败 | 驱动不支持扩容或后端容量不足 | 查resizer日志 | 检查allowVolumeExpansion和后端容量 |
| Pod删除后卷未删除 | reclaimPolicy=Retain或DeleteVolume失败 | kubectl get pv | 手动删除PV或修复驱动 |
| 多Pod写冲突 | RWO卷被多Pod挂载(不应发生但可能因调度bug) | kubectl get pod -o wide | 检查accessMode和调度约束 |
# 用csi-sanity工具测试驱动是否符合CSI规范
# https://github.com/kubernetes-csi/csi-test
docker run -v /var/run/csi/csi.sock:/csi/csi.sock \
golang:1.21 bash -c '
go install github.com/kubernetes-csi/csi-test/v5/cmd/csi-sanity@latest
$GOPATH/bin/csi-sanity --csi.endpoint=/csi/csi.sock
'
# 在节点上检查实际mount
mount | grep kubelet
# /dev/sdb on /var/lib/kubelet/staging/xxx type ext4 (rw,relatime)
# /var/lib/kubelet/staging/xxx on /var/lib/kubelet/pods/yyy/volumes/... type none (rw,bind)
# 检查VolumeAttachment对象
kubectl get volumeattachment
# NAME ATTACHER PV NODE ATTACHED
# csi-aaa nfs.csi.simple... pvc-xxx node-1 true
# 检查CSINode对象
kubectl get csinode node-1 -o yaml
# apiVersion: storage.k8s.io/v1
# kind: CSINode
# spec:
# drivers:
# - name: nfs.csi.simple.example.com
# nodeID: node-1
# allocatable:
# count: 5 # 最大可attach卷数
某集群频繁出现"too many mount points"错误。根因:CSI驱动的NodeUnpublishVolume实现有bug——umount失败时不报错只记日志,导致mount点泄漏。每次Pod重建增加一个mount点,最终达到内核/proc/sys/fs/mount-max上限。解决方案:①修复驱动确保umount失败时返回error;②设置mount-max到100000;③用umount -l(lazy umount)处理忙挂载。
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshotClass
metadata:
name: nfs-snapshot
driver: nfs.csi.simple.example.com
deletionPolicy: Delete
---
apiVersion: snapshot.storage.k8s.io/v1
kind: VolumeSnapshot
metadata:
name: pvc-snap
spec:
volumeSnapshotClassName: nfs-snapshot
source:
persistentVolumeClaimName: test-pvc # 对哪个PVC做快照
快照的CSI调用:CreateSnapshot(volume_id) → snapshot_id。恢复时创建新PVC指定dataSource为快照:
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: restored-pvc
spec:
storageClassName: nfs-simple
accessModes: [ReadWriteMany]
resources:
requests: {storage: 5Gi}
dataSource:
name: pvc-snap
kind: VolumeSnapshot
apiGroup: snapshot.storage.k8s.io
CSI拓扑感知让驱动限制卷只在某些节点可用(如:本地SSD只在有该磁盘的节点)。通过AccessibleTopology实现:
func (s *ControllerServer) CreateVolume(
ctx context.Context, req *csi.CreateVolumeRequest,
) (*csi.CreateVolumeResponse, error) {
// 从请求中获取拓扑要求
// WaitForFirstConsumer模式下,这里会收到调度器选定的拓扑
topology := req.AccessibilityRequirements.GetRequisite()
// topology = [{topology.kubernetes.io/zone: us-east-1a}]
zone := topology[0].GetSegments()["topology.kubernetes.io/zone"]
// 在指定zone创建卷
volumeID, err := s.backend.CreateVolumeInZone(ctx, zone, req.Name)
if err != nil {
return nil, err
}
return &csi.CreateVolumeResponse{
Volume: &csi.Volume{
VolumeId: volumeID,
AccessibleTopology: []*csi.Topology{
{Segments: map[string]string{
"topology.kubernetes.io/zone": zone,
}},
},
},
}, nil
}
CSI驱动可以支持ephemeral模式——卷定义在Pod spec中,不经过PVC/PV:
apiVersion: v1
kind: Pod
metadata:
name: ephemeral-pod
spec:
containers:
- name: app
image: myapp
volumeMounts:
- name: ephemeral-data
mountPath: /data
volumes:
- name: ephemeral-data
csi:
driver: nfs.csi.simple.example.com
volumeAttributes:
server: nfs.example.com
share: /ephemeral/myapp
# 无需PVC,Pod删除时卷自动清理
| 检查项 | 说明 | 状态 |
|---|---|---|
| 幂等性 | 所有方法对重复调用返回相同结果 | □ |
| 错误处理 | 返回正确的gRPC code,不panic | □ |
| 并发安全 | 多请求并发不产生竞态 | □ |
| 超时处理 | 长操作支持context取消 | □ |
| 日志 | 结构化日志,含volume_id/request_id | □ |
| 指标 | 暴露Prometheus指标(操作延迟/成功率) | □ |
| 健康检查 | Probe()正确反映后端状态 | □ |
| leader election | Controller多副本时选主 | □ |
| mount清理 | NodeUnpublish/Unstage确保umount成功 | □ |
| 维度 | 默认 | 调优建议 |
|---|---|---|
| provisioner并发 | 10 | 大集群调到50:--worker-threads=50 |
| attacher并发 | 10 | 同上 |
| CSI gRPC超时 | 无 | 设15s:--timeout=15s |
| 操作重试 | 5次 | 对慢后端调到10次 |
| mount选项 | 默认 | NFS加rsize=1048576,wsize=1048576 |
CSI Node Pod通常需要privileged: true来执行mount命令。这意味着它有完整的节点root权限。安全建议:①用最小RBAC权限给ServiceAccount;②限制CSI Pod只调度到特定节点(taint/toleration);③用SELinux/AppArmor限制CSI Pod能力;④审计CSI驱动的mount操作日志。
某MySQL集群在线扩容PVC(从500Gi到1Ti),扩容期间数据库IO hang 30秒。根因:CSI驱动的NodeExpandVolume执行了resize2fs,而ext4在线resize需要短暂冻结文件系统。解决方案:①使用xfs替代ext4(xfs在线resize无冻结);②在低峰期扩容;③对关键数据库使用离线扩容(停Pod→扩容→启Pod)。
某集群跨3个AZ,Pod在AZ-A调度但PVC的卷在AZ-B创建。根因:StorageClass用volumeBindingMode: Immediate,PVC在Pod调度前就绑定了AZ-B的PV。解决方案:改为WaitForFirstConsumer,让PVC等Pod调度后再绑定同AZ的PV。
| 核心知识点 | 掌握程度自评 |
|---|---|
| 三代存储接口演进 | □ 已掌握 □ 需复习 □ 未掌握 |
| PV/PVC/StorageClass关系 | □ 已掌握 □ 需复习 □ 未掌握 |
| CSI三个gRPC Service | □ 已掌握 □ 需复习 □ 未掌握 |
| Volume生命周期CSI调用序列 | □ 已掌握 □ 需复习 □ 未掌握 |
| NodeStage vs NodePublish | □ 已掌握 □ 需复习 □ 未掌握 |
| CSI驱动开发流程 | □ 已掌握 □ 需复习 □ 未掌握 |
| Sidecar组件职责 | □ 已掌握 □ 需复习 □ 未掌握 |
| mountPropagation原理 | □ 已掌握 □ 需复习 □ 未掌握 |
| 存储排障决策树 | □ 已掌握 □ 需复习 □ 未掌握 |
| 拓扑感知与WaitForFirstConsumer | □ 已掌握 □ 需复习 □ 未掌握 |
NodeStageVolume和NodePublishVolume为什么要分两步?如果只用一个方法同时做格式化+mount+bind mount会有什么问题?CreateVolume中实现容量配额(用NFS的quota命令限制每个share的大小)。测试创建超过配额的文件时是否被拒绝。CreateSnapshot/DeleteSnapshot)。NFS快照可以用cp -r简单实现。测试创建快照→删除原数据→从快照恢复→验证数据。