Kubernetes 高级工程师教程

第21章 Volume/PV/PVC/CSI体系与CSI驱动开发

从emptyDir到CSI gRPC接口的三个Identity/Controller/Node Service,再到Volume Attach/Mount的完整kubelet调用链与自定义CSI驱动开发——本章把K8s存储体系拆到gRPC方法签名和内核mount系统调用层面。

系列 Kubernetes 高级工程师教程 篇章 存储篇 章节 第21章 / 共46章 难度 ★★★★★ 预计阅读 60分钟 前置知识 Volume概念、PV/PVC、gRPC、Linux mount

1K8s存储体系全景:从Volume到CSI

K8s的存储体系经历了三代演进:in-tree Volume插件 → FlexVolume → CSI(Container Storage Interface)。理解这个演进过程是理解当前存储架构的前提。

1.1 三代存储接口对比

维度in-tree VolumeFlexVolumeCSI
实现位置k8s源码树内节点上的脚本/binary独立容器化组件
接口协议Go接口JSON+命令行gRPC (protobuf)
生命周期绑定k8s版本节点部署独立发布
可扩展性需改k8s源码放脚本即可标准CSI spec
跨平台是弱(依赖bash)是(gRPC跨语言)
当前状态迁移到CSI (1.26+)已废弃唯一推荐方式

1.2 存储卷类型分类

类别类型生命周期典型用途
临时存储emptyDirPod删除时清除缓存、临时文件
临时存储configMap/secret/downwardAPIPod删除时清除配置注入
节点本地hostPath持久(节点级)daemonset访问节点文件
节点本地local持久(节点级)高性能本地存储
网络存储nfs/iscsi/cephfs/glusterfs持久共享文件系统
块存储PV (CSI)持久数据库、有状态应用
投射projectedPod删除时清除多源配置合并
CSI ephemeralcsi (ephemeral mode)Pod删除时清除临时CSI卷

1.3 PV/PVC/StorageClass三角关系

存储控制平面关系
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创建磁盘)。

2CSI规范深度解析:三个gRPC Service

CSI(Container Storage Interface)是K8s/Containerd/Mesos等容器编排系统共同遵循的存储接口标准。规范定义在container-storage-interface/spec,当前版本1.9.0。

2.1 CSI架构总览

CSI组件架构
┌─────────────────────────────────────────────────┐
│                 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后端)  │
              └────────────────┘

2.2 三个gRPC Service

CSI规范定义了三个gRPC Service,每个驱动必须实现:

Identity Service

csi.v1.Identity

驱动身份标识。所有组件(controller和node)都需实现。

方法:GetPluginInfo(返回驱动名+版本)、GetPluginCapabilities(声明支持的功能)、Probe(健康检查)

Controller Service

csi.v1.Controller

卷的控制面操作(创建/删除/attach/snapshot/扩容)。通常以StatefulSet运行,单实例。

方法:CreateVolume/DeleteVolume/ControllerPublishVolume/ControllerUnpublishVolume/CreateSnapshot/DeleteSnapshot/ControllerExpandVolume

Node Service

csi.v1.Node

节点上的卷操作(mount/umount/格式化)。以DaemonSet运行,每节点一个实例。

方法:NodeStageVolume/NodeUnstageVolume/NodePublishVolume/NodeUnpublishVolume/NodeExpandVolume/NodeGetCapabilities/NodeGetInfo

2.3 核心gRPC接口签名

Protobuf (CSI v1)
// 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) {}
}

2.4 Volume生命周期与CSI调用序列

一个动态provisioned CSI卷的完整生命周期:

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)
          └─ 删除后端存储卷
Stage vs Publish的区别

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"两步。

3CSI Driver开发实战

本节开发一个最小可用的CSI驱动——nfs-csi-simple,它在后端用NFS server提供存储。

3.1 项目骨架

项目结构
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

3.2 Identity Service实现

Go - identity.go
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
}

3.3 Controller Service实现

Go - controller.go (核心方法)
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}
}

3.4 Node Service实现

Go - node.go (核心方法)
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
}

3.5 驱动入口与gRPC Server启动

Go - main.go
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)
    }
}

4CSI驱动部署与Sidecar组件

CSI驱动本身只是gRPC server,还需要一组sidecar容器来桥接K8s API和CSI gRPC接口。

4.1 Sidecar组件清单

组件运行位置职责
external-provisionerController Podwatch PVC,调CreateVolume/DeleteVolume
external-attacherController Podwatch VolumeAttachment,调ControllerPublish/Unpublish
external-snapshotterController Podwatch VolumeSnapshot,调CreateSnapshot/DeleteSnapshot
external-resizerController Podwatch PVC扩容请求,调ControllerExpandVolume
node-driver-registrarNode Pod (DaemonSet)向kubelet注册CSI驱动(创建CSINode对象)
external-health-monitorController/Node Pod监控卷健康状态,更新PV/PVC事件
liveness-probeController/Node Pod调Probe()做健康检查,更新CSI驱动健康状态

4.2 Controller部署YAML

YAML - Controller StatefulSet
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: {}

4.3 Node DaemonSet YAML

YAML - Node DaemonSet
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
关键:mountPropagation: Bidirectional

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能力。

5StorageClass与CSI参数传递

StorageClass是用户与CSI驱动之间的参数传递桥梁。StorageClass的parameters字段会传递给CSI驱动的CreateVolume调用。

YAML - StorageClass
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

5.1 参数传递路径

来源字段传递到CSI方法字段
StorageClassparametersCreateVolumereq.Parameters
StorageClassmountOptionsNodeStageVolumereq.VolumeCapability.MountVolume.MountFlags
StorageClassreclaimPolicy—(由provisioner处理)—
PVCresources.requests.storageCreateVolumereq.CapacityRange.RequiredBytes
PVCaccessModesCreateVolumereq.VolumeCapabilities
PVCspec.dataSource (snapshot)CreateVolumereq.VolumeContentSource
SecretStorageClass.secretCreateVolumereq.Secrets
VolumeContextCreateVolume返回的NodeStageVolumereq.VolumeContext

6动手实验:部署并测试自定义CSI驱动

Step 1:准备NFS server

Bash
# 在集群中部署一个NFS server用于测试
kubectl apply -f - <

Step 2:构建并部署CSI驱动

Bash
# 构建镜像
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

Step 3:创建PVC并测试

Bash
# 创建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

Step 4:测试扩容

Bash
# 扩容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

Step 5:观察CSI gRPC调用日志

Bash
# 查看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

7存储排障指南

7.1 排障决策树

排障流程
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 检查挂载点权限

7.2 常见故障对照表

现象可能根因诊断命令解决方案
PVC一直PendingStorageClass不存在或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为rodmesg | grep -i "read-only"修复后端,重新挂载
扩容失败驱动不支持扩容或后端容量不足查resizer日志检查allowVolumeExpansion和后端容量
Pod删除后卷未删除reclaimPolicy=Retain或DeleteVolume失败kubectl get pv手动删除PV或修复驱动
多Pod写冲突RWO卷被多Pod挂载(不应发生但可能因调度bug)kubectl get pod -o wide检查accessMode和调度约束

7.3 高级诊断:直接检查CSI gRPC

Bash
# 用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卷数
生产故障:mount泄漏

某集群频繁出现"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)处理忙挂载。

8高级CSI特性

8.1 快照与恢复

YAML - VolumeSnapshot
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为快照:

YAML - 从快照恢复
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

8.2 拓扑感知

CSI拓扑感知让驱动限制卷只在某些节点可用(如:本地SSD只在有该磁盘的节点)。通过AccessibleTopology实现:

Go - 拓扑感知CreateVolume
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
}

8.3 CSI Ephemeral Inline Volume

CSI驱动可以支持ephemeral模式——卷定义在Pod spec中,不经过PVC/PV:

YAML - Ephemeral CSI Volume
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删除时卷自动清理

9生产实践与最佳实践

9.1 CSI驱动生产检查清单

检查项说明状态
幂等性所有方法对重复调用返回相同结果□
错误处理返回正确的gRPC code,不panic□
并发安全多请求并发不产生竞态□
超时处理长操作支持context取消□
日志结构化日志,含volume_id/request_id□
指标暴露Prometheus指标(操作延迟/成功率)□
健康检查Probe()正确反映后端状态□
leader electionController多副本时选主□
mount清理NodeUnpublish/Unstage确保umount成功□

9.2 性能调优

维度默认调优建议
provisioner并发10大集群调到50:--worker-threads=50
attacher并发10同上
CSI gRPC超时无设15s:--timeout=15s
操作重试5次对慢后端调到10次
mount选项默认NFS加rsize=1048576,wsize=1048576

9.3 安全考量

CSI驱动的安全风险

CSI Node Pod通常需要privileged: true来执行mount命令。这意味着它有完整的节点root权限。安全建议:①用最小RBAC权限给ServiceAccount;②限制CSI Pod只调度到特定节点(taint/toleration);③用SELinux/AppArmor限制CSI Pod能力;④审计CSI驱动的mount操作日志。

10生产案例与思考题

10.1 案例:PVC扩容导致数据库IO hang

某MySQL集群在线扩容PVC(从500Gi到1Ti),扩容期间数据库IO hang 30秒。根因:CSI驱动的NodeExpandVolume执行了resize2fs,而ext4在线resize需要短暂冻结文件系统。解决方案:①使用xfs替代ext4(xfs在线resize无冻结);②在低峰期扩容;③对关键数据库使用离线扩容(停Pod→扩容→启Pod)。

10.2 案例:多可用区卷跨区挂载失败

某集群跨3个AZ,Pod在AZ-A调度但PVC的卷在AZ-B创建。根因:StorageClass用volumeBindingMode: Immediate,PVC在Pod调度前就绑定了AZ-B的PV。解决方案:改为WaitForFirstConsumer,让PVC等Pod调度后再绑定同AZ的PV。

10.3 知识点检查表

核心知识点掌握程度自评
三代存储接口演进□ 已掌握 □ 需复习 □ 未掌握
PV/PVC/StorageClass关系□ 已掌握 □ 需复习 □ 未掌握
CSI三个gRPC Service□ 已掌握 □ 需复习 □ 未掌握
Volume生命周期CSI调用序列□ 已掌握 □ 需复习 □ 未掌握
NodeStage vs NodePublish□ 已掌握 □ 需复习 □ 未掌握
CSI驱动开发流程□ 已掌握 □ 需复习 □ 未掌握
Sidecar组件职责□ 已掌握 □ 需复习 □ 未掌握
mountPropagation原理□ 已掌握 □ 需复习 □ 未掌握
存储排障决策树□ 已掌握 □ 需复习 □ 未掌握
拓扑感知与WaitForFirstConsumer□ 已掌握 □ 需复习 □ 未掌握

10.4 思考题

  1. 原理题:为什么CSI规范将Controller Service和Node Service分开?如果合并成一个Service会有什么问题?提示:考虑部署模式、故障域、权限。
  2. 原理题:NodeStageVolume和NodePublishVolume为什么要分两步?如果只用一个方法同时做格式化+mount+bind mount会有什么问题?
  3. 实操题:修改本章的NFS CSI驱动,在CreateVolume中实现容量配额(用NFS的quota命令限制每个share的大小)。测试创建超过配额的文件时是否被拒绝。
  4. 实操题:为NFS CSI驱动添加快照功能(CreateSnapshot/DeleteSnapshot)。NFS快照可以用cp -r简单实现。测试创建快照→删除原数据→从快照恢复→验证数据。
  5. 分析题:某集群有1000个PVC,每次节点重启后所有Pod的卷重新mount需要10分钟。分析瓶颈在哪里,给出优化方案。提示:考虑provisioner并发、attacher并发、CSI驱动的NodePublishVolume并发。
  6. 设计题:设计一个支持跨集群卷迁移的CSI驱动扩展。要求:卷从cluster-A迁移到cluster-B时,数据不丢失、应用停机时间最短。考虑:rsync、快照、存储后端原生复制。
  7. 排障题:PVC状态为Bound,Pod状态为ContainerCreating,事件报"MountVolume.MountDevice failed for volume: nfs mount failed: mount.nfs: Connection timed out"。列出至少5个可能根因和对应的诊断命令。