← Back to Pull requests

Implement Content Addressable Storage via CSI #15

Merged
codebot-robot merged 13 files (1481 lines) on Jun 18, 2026 22:39 UTC
View on GitHub
codebot-robot codebot-robot commented on Jun 18, 2026 12:04 UTC
Author

This PR implements Content Addressable Storage (CAS) support in the in-cluster-storage (AgentFS) CSI driver.

Solution Details:


  • CAS Server & Client (pkg/cas): Implements a lightweight Unix Domain Socket server that binds to a well-known path inside the volume (.in-cluster-storage/api) and communicates with clients. It supports the GET <sha256> protocol to lookup blobs in a central host-level directory and pass an open file descriptor using SCM_RIGHTS (ancillary control messages).

  • CSI Driver Integration: Integrates the CAS server lifecycle into NodePublishVolume (starting after mount) and NodeUnpublishVolume (safely stopping and cleaning up before unmount to avoid EBUSY).

  • Research Document: Documented all architectural decisions, OverlayFS findings, namespace traversal, and unmount safety in docs/research/cas.md.

  • Testing: Added complete unit tests for the CAS server/client, and added E2E assertions to verify the presence and visibility of the custom socket inside target pods.
  • Fixes #14

    Diff: 1481 lines (+1481 / -0) across 13 files Reviewer: justinsb Review duration: 635m
    All Vouch review confidence checks passed
    Residual risk 0.07 = Change Risk (0.61) × (1 − Review Confidence (0.89)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.61 · 1481 lines diff across 13 files
    0.61
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.88 · 5 substantive comment(s)
    0.88
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    88%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.400
    Real PR Conversation Timeline
    18 items
    justinsb justinsb commented on code on Jun 18, 2026 14:14 UTC
    Code Review
    pkg/cas/cas_test.go:1
    @@ -0,0 +1,106 @@
    +/*
    +Copyright 2026 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 cas
    +
    +import (
    +	"context"
    +	"io"
    +	"os"
    +	"path/filepath"
    +	"testing"
    +)
    +
    +type mockDownloader struct {
    +	content map[string]string
    +}
    +
    +func (m *mockDownloader) DownloadBlob(ctx context.Context, sha string, destPath string) error {
    +	data, exists := m.content[sha]
    +	if !exists {
    +		return os.ErrNotExist
    +	}
    +	return os.WriteFile(destPath, []byte(data), 0644)
    +}
    +
    +func TestCASServerAndClient(t *testing.T) {

    I would rather we created an e2e test than lots of tiny unit tests; unit tests tend to ossify the implementation

    justinsb justinsb commented on code on Jun 18, 2026 14:15 UTC
    Code Review
    pkg/cas/server.go:1
    @@ -0,0 +1,221 @@
    +/*
    +Copyright 2026 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 cas
    +
    +import (
    +	"bufio"
    +	"context"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net"
    +	"os"
    +	"path/filepath"
    +	"regexp"
    +	"strings"
    +	"sync"
    +
    +	"golang.org/x/sys/unix"
    +	"k8s.io/klog/v2"
    +)
    +
    +var shaRegex = regexp.MustCompile(`^[a-fA-F0-9]{64}$`)

    Please don't use a regex for something which is trivial to write as go code.

    justinsb justinsb commented on code on Jun 18, 2026 14:16 UTC
    Code Review
    cas/pkg/cas/client.go:1
    @@ -0,0 +1,105 @@
    +/*
    +Copyright 2026 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 cas
    +
    +import (
    +	"fmt"
    +	"net"
    +	"os"
    +	"strconv"
    +	"strings"
    +	"syscall"
    +
    +	"golang.org/x/sys/unix"
    +)
    +
    +// Client represents a client for the CAS UDS server.
    +type Client struct {
    +	socketPath string
    +}
    +
    +// NewClient creates a new Client pointing to the given UDS socketPath.
    +func NewClient(socketPath string) *Client {
    +	return &Client{socketPath: socketPath}
    +}
    +
    +// RequestBlob requests the blob with the given SHA256 from the CAS server,
    +// and returns the open *os.File pointing to that blob (using SCM_RIGHTS) along with the file size.
    +func (c *Client) RequestBlob(sha string) (*os.File, int64, error) {
    +	conn, err := net.Dial("unix", c.socketPath)
    +	if err != nil {
    +		return nil, 0, fmt.Errorf("failed to connect to CAS socket %s: %v", c.socketPath, err)
    +	}
    +	defer conn.Close()
    +
    +	unixConn, ok := conn.(*net.UnixConn)
    +	if !ok {
    +		return nil, 0, fmt.Errorf("connection is not a unix connection")
    +	}
    +
    +	req := fmt.Sprintf("GET %s\n", sha)

    Let's just use GRPC, rather than implementing our own protocol (assuming we can do that)

    justinsb justinsb commented on Jun 18, 2026 14:17 UTC
    Contributor

    Impressive stuff. But let's create a separate CSI driver, not tied to agentfs. Let's create cas/ and put all our logic underneath it. If we create cas/.ap/ then ap should pick up on this as a "subproject".

    We'll likely similarly move agentfs into its own subproject in future, but let's start with cas/

    justinsb justinsb commented on code on Jun 18, 2026 15:32 UTC
    Code Review
    cas/cmd/cas-client-test/main.go:1
    @@ -0,0 +1,51 @@
    +/*
    +Copyright 2026 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 main
    +
    +import (
    +	"fmt"
    +	"io"
    +	"os"
    +
    +	"github.com/gke-labs/in-cluster-storage/cas/pkg/cas"
    +)
    +
    +func main() {
    +	if len(os.Args) < 3 {
    +		fmt.Println("Usage: cas-client-test <socket_path> <sha256>")
    +		os.Exit(1)
    +	}
    +
    +	socketPath := os.Args[1]
    +	sha := os.Args[2]
    +
    +	client := cas.NewClient(socketPath)
    +	file, size, err := client.RequestBlob(sha)
    +	if err != nil {
    +		fmt.Printf("Error requesting blob: %v\n", err)
    +		os.Exit(1)
    +	}
    +	defer file.Close()
    +
    +	fmt.Printf("SUCCESS size=%d\n", size)

    We might as well also compute and print the sha256 sum, to verify that we read it correctly!

    justinsb justinsb commented on code on Jun 18, 2026 15:34 UTC
    Code Review
    cas/cmd/cas-node-daemon/main.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2026 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 main
    +
    +import (
    +	"context"
    +	"flag"
    +	"fmt"
    +	"io"
    +	"net"
    +	"os"
    +	"path/filepath"
    +	"strings"
    +	"sync"
    +	"syscall"
    +
    +	"github.com/container-storage-interface/spec/lib/go/csi"
    +	pb "github.com/gke-labs/in-cluster-storage/pkg/api/v1alpha1"
    +	"github.com/gke-labs/in-cluster-storage/cas/pkg/cas"
    +	"google.golang.org/grpc"
    +	"google.golang.org/grpc/credentials/insecure"
    +	"k8s.io/klog/v2"
    +)
    +
    +var (
    +	endpoint          = flag.String("endpoint", "unix:///tmp/csi.sock", "CSI endpoint")
    +	nodeID            = flag.String("nodeid", "", "node id")
    +	storagePath       = flag.String("storage-path", "/var/lib/cas", "Base path for storage")

    Should we use /var/cache/cas instead?

    justinsb justinsb commented on code on Jun 18, 2026 15:35 UTC
    Code Review
    cas/cmd/cas-node-daemon/main.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2026 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 main
    +
    +import (
    +	"context"
    +	"flag"
    +	"fmt"
    +	"io"
    +	"net"
    +	"os"
    +	"path/filepath"
    +	"strings"
    +	"sync"
    +	"syscall"
    +
    +	"github.com/container-storage-interface/spec/lib/go/csi"
    +	pb "github.com/gke-labs/in-cluster-storage/pkg/api/v1alpha1"
    +	"github.com/gke-labs/in-cluster-storage/cas/pkg/cas"
    +	"google.golang.org/grpc"
    +	"google.golang.org/grpc/credentials/insecure"
    +	"k8s.io/klog/v2"
    +)
    +
    +var (
    +	endpoint          = flag.String("endpoint", "unix:///tmp/csi.sock", "CSI endpoint")
    +	nodeID            = flag.String("nodeid", "", "node id")
    +	storagePath       = flag.String("storage-path", "/var/lib/cas", "Base path for storage")
    +	controllerAddress = flag.String("controller-address", "agentfs-controller:50051", "AgentFS Controller address")
    +)
    +
    +func main() {
    +	klog.InitFlags(nil)
    +	flag.Parse()
    +
    +	if *nodeID == "" {
    +		klog.Fatal("nodeid must be provided")
    +	}
    +
    +	if err := os.MkdirAll(*storagePath, 0755); err != nil {
    +		klog.Fatalf("failed to create storage path %s: %v", *storagePath, err)
    +	}
    +
    +	proto, addr, err := parseEndpoint(*endpoint)
    +	if err != nil {
    +		klog.Fatal(err)
    +	}
    +
    +	if proto == "unix" {
    +		addr = filepath.FromSlash(addr)
    +		if err := os.Remove(addr); err != nil && !os.IsNotExist(err) {
    +			klog.Fatalf("failed to remove %s: %v", addr, err)
    +		}
    +	}
    +
    +	listener, err := net.Listen(proto, addr)
    +	if err != nil {
    +		klog.Fatalf("failed to listen: %v", err)
    +	}
    +
    +	server := grpc.NewServer()
    +
    +	downloader := &controllerDownloader{
    +		controllerAddress: *controllerAddress,
    +	}
    +
    +	driver := &casCSIDriver{
    +		nodeID:     *nodeID,
    +		downloader: downloader,
    +		casServers: make(map[string]*cas.Server),
    +	}
    +
    +	csi.RegisterIdentityServer(server, driver)
    +	csi.RegisterNodeServer(server, driver)
    +
    +	klog.Infof("CAS CSI driver listening on %s", *endpoint)
    +	if err := server.Serve(listener); err != nil {
    +		klog.Fatalf("failed to serve: %v", err)
    +	}
    +}
    +
    +func parseEndpoint(endpoint string) (string, string, error) {
    +	parts := strings.SplitN(endpoint, "://", 2)
    +	if len(parts) != 2 {
    +		return "", "", fmt.Errorf("invalid endpoint: %s", endpoint)
    +	}
    +	scheme, addr := parts[0], parts[1]
    +	if scheme != "unix" && scheme != "tcp" {
    +		return "", "", fmt.Errorf("invalid endpoint: %s", endpoint)
    +	}
    +	return scheme, addr, nil
    +}
    +
    +type controllerDownloader struct {
    +	controllerAddress string
    +	conn              *grpc.ClientConn
    +	mu                sync.Mutex
    +}
    +
    +func (d *controllerDownloader) DownloadBlob(ctx context.Context, sha string, destPath string) error {
    +	d.mu.Lock()
    +	if d.conn == nil {
    +		conn, err := grpc.Dial(d.controllerAddress, grpc.WithTransportCredentials(insecure.NewCredentials()))
    +		if err != nil {
    +			d.mu.Unlock()
    +			return err
    +		}
    +		d.conn = conn
    +	}
    +	d.mu.Unlock()
    +
    +	client := pb.NewAgentFSControllerClient(d.conn)
    +	stream, err := client.DownloadBlob(ctx, &pb.DownloadBlobRequest{Sha256: sha})
    +	if err != nil {
    +		return err
    +	}
    +
    +	f, err := os.Create(destPath)

    Let's save to a temp file and rename (be careful to check for errors when calling close also, as that is a common mistake). Maybe create a helper function for this.

    justinsb justinsb commented on code on Jun 18, 2026 15:37 UTC
    Code Review
    cas/cmd/cas-node-daemon/main.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2026 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 main
    +
    +import (
    +	"context"
    +	"flag"
    +	"fmt"
    +	"io"
    +	"net"
    +	"os"
    +	"path/filepath"
    +	"strings"
    +	"sync"
    +	"syscall"
    +
    +	"github.com/container-storage-interface/spec/lib/go/csi"
    +	pb "github.com/gke-labs/in-cluster-storage/pkg/api/v1alpha1"
    +	"github.com/gke-labs/in-cluster-storage/cas/pkg/cas"
    +	"google.golang.org/grpc"
    +	"google.golang.org/grpc/credentials/insecure"
    +	"k8s.io/klog/v2"
    +)
    +
    +var (
    +	endpoint          = flag.String("endpoint", "unix:///tmp/csi.sock", "CSI endpoint")
    +	nodeID            = flag.String("nodeid", "", "node id")
    +	storagePath       = flag.String("storage-path", "/var/lib/cas", "Base path for storage")
    +	controllerAddress = flag.String("controller-address", "agentfs-controller:50051", "AgentFS Controller address")
    +)
    +
    +func main() {
    +	klog.InitFlags(nil)
    +	flag.Parse()
    +
    +	if *nodeID == "" {
    +		klog.Fatal("nodeid must be provided")
    +	}
    +
    +	if err := os.MkdirAll(*storagePath, 0755); err != nil {
    +		klog.Fatalf("failed to create storage path %s: %v", *storagePath, err)
    +	}
    +
    +	proto, addr, err := parseEndpoint(*endpoint)
    +	if err != nil {
    +		klog.Fatal(err)
    +	}
    +
    +	if proto == "unix" {
    +		addr = filepath.FromSlash(addr)
    +		if err := os.Remove(addr); err != nil && !os.IsNotExist(err) {
    +			klog.Fatalf("failed to remove %s: %v", addr, err)
    +		}
    +	}
    +
    +	listener, err := net.Listen(proto, addr)
    +	if err != nil {
    +		klog.Fatalf("failed to listen: %v", err)
    +	}
    +
    +	server := grpc.NewServer()
    +
    +	downloader := &controllerDownloader{
    +		controllerAddress: *controllerAddress,
    +	}
    +
    +	driver := &casCSIDriver{
    +		nodeID:     *nodeID,
    +		downloader: downloader,
    +		casServers: make(map[string]*cas.Server),
    +	}
    +
    +	csi.RegisterIdentityServer(server, driver)
    +	csi.RegisterNodeServer(server, driver)
    +
    +	klog.Infof("CAS CSI driver listening on %s", *endpoint)
    +	if err := server.Serve(listener); err != nil {
    +		klog.Fatalf("failed to serve: %v", err)
    +	}
    +}
    +
    +func parseEndpoint(endpoint string) (string, string, error) {
    +	parts := strings.SplitN(endpoint, "://", 2)
    +	if len(parts) != 2 {
    +		return "", "", fmt.Errorf("invalid endpoint: %s", endpoint)
    +	}
    +	scheme, addr := parts[0], parts[1]
    +	if scheme != "unix" && scheme != "tcp" {
    +		return "", "", fmt.Errorf("invalid endpoint: %s", endpoint)
    +	}
    +	return scheme, addr, nil
    +}
    +
    +type controllerDownloader struct {
    +	controllerAddress string
    +	conn              *grpc.ClientConn
    +	mu                sync.Mutex
    +}
    +
    +func (d *controllerDownloader) DownloadBlob(ctx context.Context, sha string, destPath string) error {
    +	d.mu.Lock()
    +	if d.conn == nil {
    +		conn, err := grpc.Dial(d.controllerAddress, grpc.WithTransportCredentials(insecure.NewCredentials()))
    +		if err != nil {
    +			d.mu.Unlock()
    +			return err
    +		}
    +		d.conn = conn
    +	}
    +	d.mu.Unlock()
    +
    +	client := pb.NewAgentFSControllerClient(d.conn)
    +	stream, err := client.DownloadBlob(ctx, &pb.DownloadBlobRequest{Sha256: sha})
    +	if err != nil {
    +		return err
    +	}
    +
    +	f, err := os.Create(destPath)
    +	if err != nil {
    +		return err
    +	}
    +	defer f.Close()
    +
    +	buffer := make([]byte, 1024*1024)
    +	for {
    +		resp, err := stream.Recv()
    +		if err == io.EOF {
    +			break
    +		}
    +		if err != nil {
    +			return err
    +		}
    +		// Write in chunks
    +		if _, err := f.Write(resp.Content); err != nil {
    +			return err
    +		}
    +		_ = buffer

    Not sure what this is for; can you please add a comment - this looks like either a pure hallucination or a clever GC trick

    justinsb justinsb commented on code on Jun 18, 2026 15:38 UTC
    Code Review
    cas/cmd/cas-node-daemon/main.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2026 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 main
    +
    +import (
    +	"context"
    +	"flag"
    +	"fmt"
    +	"io"
    +	"net"
    +	"os"
    +	"path/filepath"
    +	"strings"
    +	"sync"
    +	"syscall"
    +
    +	"github.com/container-storage-interface/spec/lib/go/csi"
    +	pb "github.com/gke-labs/in-cluster-storage/pkg/api/v1alpha1"
    +	"github.com/gke-labs/in-cluster-storage/cas/pkg/cas"
    +	"google.golang.org/grpc"
    +	"google.golang.org/grpc/credentials/insecure"
    +	"k8s.io/klog/v2"
    +)
    +
    +var (
    +	endpoint          = flag.String("endpoint", "unix:///tmp/csi.sock", "CSI endpoint")
    +	nodeID            = flag.String("nodeid", "", "node id")
    +	storagePath       = flag.String("storage-path", "/var/lib/cas", "Base path for storage")
    +	controllerAddress = flag.String("controller-address", "agentfs-controller:50051", "AgentFS Controller address")
    +)
    +
    +func main() {
    +	klog.InitFlags(nil)
    +	flag.Parse()
    +
    +	if *nodeID == "" {
    +		klog.Fatal("nodeid must be provided")
    +	}
    +
    +	if err := os.MkdirAll(*storagePath, 0755); err != nil {
    +		klog.Fatalf("failed to create storage path %s: %v", *storagePath, err)
    +	}
    +
    +	proto, addr, err := parseEndpoint(*endpoint)
    +	if err != nil {
    +		klog.Fatal(err)
    +	}
    +
    +	if proto == "unix" {
    +		addr = filepath.FromSlash(addr)
    +		if err := os.Remove(addr); err != nil && !os.IsNotExist(err) {
    +			klog.Fatalf("failed to remove %s: %v", addr, err)
    +		}
    +	}
    +
    +	listener, err := net.Listen(proto, addr)
    +	if err != nil {
    +		klog.Fatalf("failed to listen: %v", err)
    +	}
    +
    +	server := grpc.NewServer()
    +
    +	downloader := &controllerDownloader{
    +		controllerAddress: *controllerAddress,
    +	}
    +
    +	driver := &casCSIDriver{
    +		nodeID:     *nodeID,
    +		downloader: downloader,
    +		casServers: make(map[string]*cas.Server),
    +	}
    +
    +	csi.RegisterIdentityServer(server, driver)
    +	csi.RegisterNodeServer(server, driver)
    +
    +	klog.Infof("CAS CSI driver listening on %s", *endpoint)
    +	if err := server.Serve(listener); err != nil {
    +		klog.Fatalf("failed to serve: %v", err)
    +	}
    +}
    +
    +func parseEndpoint(endpoint string) (string, string, error) {
    +	parts := strings.SplitN(endpoint, "://", 2)
    +	if len(parts) != 2 {
    +		return "", "", fmt.Errorf("invalid endpoint: %s", endpoint)
    +	}
    +	scheme, addr := parts[0], parts[1]
    +	if scheme != "unix" && scheme != "tcp" {
    +		return "", "", fmt.Errorf("invalid endpoint: %s", endpoint)
    +	}
    +	return scheme, addr, nil
    +}
    +
    +type controllerDownloader struct {
    +	controllerAddress string
    +	conn              *grpc.ClientConn
    +	mu                sync.Mutex
    +}
    +
    +func (d *controllerDownloader) DownloadBlob(ctx context.Context, sha string, destPath string) error {
    +	d.mu.Lock()
    +	if d.conn == nil {
    +		conn, err := grpc.Dial(d.controllerAddress, grpc.WithTransportCredentials(insecure.NewCredentials()))
    +		if err != nil {
    +			d.mu.Unlock()
    +			return err
    +		}
    +		d.conn = conn
    +	}
    +	d.mu.Unlock()
    +
    +	client := pb.NewAgentFSControllerClient(d.conn)
    +	stream, err := client.DownloadBlob(ctx, &pb.DownloadBlobRequest{Sha256: sha})
    +	if err != nil {
    +		return err
    +	}
    +
    +	f, err := os.Create(destPath)
    +	if err != nil {
    +		return err
    +	}
    +	defer f.Close()
    +
    +	buffer := make([]byte, 1024*1024)
    +	for {
    +		resp, err := stream.Recv()
    +		if err == io.EOF {
    +			break
    +		}
    +		if err != nil {
    +			return err
    +		}
    +		// Write in chunks
    +		if _, err := f.Write(resp.Content); err != nil {
    +			return err
    +		}
    +		_ = buffer
    +	}
    +	return nil
    +}
    +
    +type casCSIDriver struct {
    +	csi.UnimplementedIdentityServer
    +	csi.UnimplementedNodeServer
    +
    +	nodeID     string
    +	downloader *controllerDownloader
    +
    +	casServersMu sync.Mutex
    +	casServers   map[string]*cas.Server
    +}
    +
    +func (d *casCSIDriver) GetPluginInfo(ctx context.Context, req *csi.GetPluginInfoRequest) (*csi.GetPluginInfoResponse, error) {
    +	return &csi.GetPluginInfoResponse{
    +		Name:          "cas.labs.gke.io",
    +		VendorVersion: "0.0.1",
    +	}, nil
    +}
    +
    +func (d *casCSIDriver) 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,
    +					},
    +				},
    +			},
    +		},
    +	}, nil
    +}
    +
    +func (d *casCSIDriver) Probe(ctx context.Context, req *csi.ProbeRequest) (*csi.ProbeResponse, error) {
    +	return &csi.ProbeResponse{}, nil
    +}
    +
    +func (d *casCSIDriver) NodeGetInfo(ctx context.Context, req *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) {
    +	return &csi.NodeGetInfoResponse{
    +		NodeId: d.nodeID,
    +	}, nil
    +}
    +
    +func (d *casCSIDriver) 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,
    +					},
    +				},
    +			},
    +		},
    +	}, nil
    +}
    +
    +func (d *casCSIDriver) NodePublishVolume(ctx context.Context, req *csi.NodePublishVolumeRequest) (*csi.NodePublishVolumeResponse, error) {
    +	targetPath := req.GetTargetPath()
    +	klog.Infof("Publishing CAS volume to %s", targetPath)
    +
    +	if err := os.MkdirAll(targetPath, 0755); err != nil {
    +		klog.Errorf("Failed to create target path %s: %v", targetPath, err)
    +		return nil, fmt.Errorf("failed to create target path %s: %v", targetPath, err)
    +	}
    +
    +	// Check if already mounted
    +	notMnt, err := isNotMountPoint(targetPath)
    +	if err != nil {
    +		klog.Errorf("Failed to check if %s is a mount point: %v", targetPath, err)
    +		return nil, fmt.Errorf("failed to check if %s is a mount point: %v", targetPath, err)
    +	}
    +
    +	if notMnt {
    +		// Mount tmpfs filesystem to targetPath
    +		klog.Infof("Mounting tmpfs on %s", targetPath)
    +		if err := syscall.Mount("tmpfs", targetPath, "tmpfs", 0, ""); err != nil {
    +			klog.Errorf("Failed to mount tmpfs to %s: %v", targetPath, err)
    +			return nil, fmt.Errorf("failed to mount tmpfs to %s: %v", targetPath, err)
    +		}
    +	}
    +
    +	// Start CAS server under targetPath/.in-cluster-storage/api
    +	casDir := filepath.Join(targetPath, ".in-cluster-storage")
    +	if err := os.MkdirAll(casDir, 0777); err != nil {
    +		klog.Errorf("Failed to create CAS socket directory %s: %v", casDir, err)
    +		return nil, fmt.Errorf("failed to create CAS socket directory: %v", err)
    +	}
    +	if err := os.Chmod(casDir, 0777); err != nil {
    +		klog.Warningf("failed to chmod CAS socket directory %s: %v", casDir, err)
    +	}
    +
    +	casSocketPath := filepath.Join(casDir, "api")
    +	_ = os.Remove(casSocketPath)

    Let's verify that if there is an error it is IsNotExists

    justinsb justinsb commented on code on Jun 18, 2026 15:39 UTC
    Code Review
    cas/cmd/cas-node-daemon/main.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2026 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 main
    +
    +import (
    +	"context"
    +	"flag"
    +	"fmt"
    +	"io"
    +	"net"
    +	"os"
    +	"path/filepath"
    +	"strings"
    +	"sync"
    +	"syscall"
    +
    +	"github.com/container-storage-interface/spec/lib/go/csi"
    +	pb "github.com/gke-labs/in-cluster-storage/pkg/api/v1alpha1"
    +	"github.com/gke-labs/in-cluster-storage/cas/pkg/cas"
    +	"google.golang.org/grpc"
    +	"google.golang.org/grpc/credentials/insecure"
    +	"k8s.io/klog/v2"
    +)
    +
    +var (
    +	endpoint          = flag.String("endpoint", "unix:///tmp/csi.sock", "CSI endpoint")
    +	nodeID            = flag.String("nodeid", "", "node id")
    +	storagePath       = flag.String("storage-path", "/var/lib/cas", "Base path for storage")
    +	controllerAddress = flag.String("controller-address", "agentfs-controller:50051", "AgentFS Controller address")
    +)
    +
    +func main() {
    +	klog.InitFlags(nil)
    +	flag.Parse()
    +
    +	if *nodeID == "" {
    +		klog.Fatal("nodeid must be provided")
    +	}
    +
    +	if err := os.MkdirAll(*storagePath, 0755); err != nil {
    +		klog.Fatalf("failed to create storage path %s: %v", *storagePath, err)
    +	}
    +
    +	proto, addr, err := parseEndpoint(*endpoint)
    +	if err != nil {
    +		klog.Fatal(err)
    +	}
    +
    +	if proto == "unix" {
    +		addr = filepath.FromSlash(addr)
    +		if err := os.Remove(addr); err != nil && !os.IsNotExist(err) {
    +			klog.Fatalf("failed to remove %s: %v", addr, err)
    +		}
    +	}
    +
    +	listener, err := net.Listen(proto, addr)
    +	if err != nil {
    +		klog.Fatalf("failed to listen: %v", err)
    +	}
    +
    +	server := grpc.NewServer()
    +
    +	downloader := &controllerDownloader{
    +		controllerAddress: *controllerAddress,
    +	}
    +
    +	driver := &casCSIDriver{
    +		nodeID:     *nodeID,
    +		downloader: downloader,
    +		casServers: make(map[string]*cas.Server),
    +	}
    +
    +	csi.RegisterIdentityServer(server, driver)
    +	csi.RegisterNodeServer(server, driver)
    +
    +	klog.Infof("CAS CSI driver listening on %s", *endpoint)
    +	if err := server.Serve(listener); err != nil {
    +		klog.Fatalf("failed to serve: %v", err)
    +	}
    +}
    +
    +func parseEndpoint(endpoint string) (string, string, error) {
    +	parts := strings.SplitN(endpoint, "://", 2)
    +	if len(parts) != 2 {
    +		return "", "", fmt.Errorf("invalid endpoint: %s", endpoint)
    +	}
    +	scheme, addr := parts[0], parts[1]
    +	if scheme != "unix" && scheme != "tcp" {
    +		return "", "", fmt.Errorf("invalid endpoint: %s", endpoint)
    +	}
    +	return scheme, addr, nil
    +}
    +
    +type controllerDownloader struct {
    +	controllerAddress string
    +	conn              *grpc.ClientConn
    +	mu                sync.Mutex
    +}
    +
    +func (d *controllerDownloader) DownloadBlob(ctx context.Context, sha string, destPath string) error {
    +	d.mu.Lock()
    +	if d.conn == nil {
    +		conn, err := grpc.Dial(d.controllerAddress, grpc.WithTransportCredentials(insecure.NewCredentials()))
    +		if err != nil {
    +			d.mu.Unlock()
    +			return err
    +		}
    +		d.conn = conn
    +	}
    +	d.mu.Unlock()
    +
    +	client := pb.NewAgentFSControllerClient(d.conn)
    +	stream, err := client.DownloadBlob(ctx, &pb.DownloadBlobRequest{Sha256: sha})
    +	if err != nil {
    +		return err
    +	}
    +
    +	f, err := os.Create(destPath)
    +	if err != nil {
    +		return err
    +	}
    +	defer f.Close()
    +
    +	buffer := make([]byte, 1024*1024)
    +	for {
    +		resp, err := stream.Recv()
    +		if err == io.EOF {
    +			break
    +		}
    +		if err != nil {
    +			return err
    +		}
    +		// Write in chunks
    +		if _, err := f.Write(resp.Content); err != nil {
    +			return err
    +		}
    +		_ = buffer
    +	}
    +	return nil
    +}
    +
    +type casCSIDriver struct {
    +	csi.UnimplementedIdentityServer
    +	csi.UnimplementedNodeServer
    +
    +	nodeID     string
    +	downloader *controllerDownloader
    +
    +	casServersMu sync.Mutex
    +	casServers   map[string]*cas.Server
    +}
    +
    +func (d *casCSIDriver) GetPluginInfo(ctx context.Context, req *csi.GetPluginInfoRequest) (*csi.GetPluginInfoResponse, error) {
    +	return &csi.GetPluginInfoResponse{
    +		Name:          "cas.labs.gke.io",
    +		VendorVersion: "0.0.1",
    +	}, nil
    +}
    +
    +func (d *casCSIDriver) 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,
    +					},
    +				},
    +			},
    +		},
    +	}, nil
    +}
    +
    +func (d *casCSIDriver) Probe(ctx context.Context, req *csi.ProbeRequest) (*csi.ProbeResponse, error) {
    +	return &csi.ProbeResponse{}, nil
    +}
    +
    +func (d *casCSIDriver) NodeGetInfo(ctx context.Context, req *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) {
    +	return &csi.NodeGetInfoResponse{
    +		NodeId: d.nodeID,
    +	}, nil
    +}
    +
    +func (d *casCSIDriver) 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,
    +					},
    +				},
    +			},
    +		},
    +	}, nil
    +}
    +
    +func (d *casCSIDriver) NodePublishVolume(ctx context.Context, req *csi.NodePublishVolumeRequest) (*csi.NodePublishVolumeResponse, error) {
    +	targetPath := req.GetTargetPath()
    +	klog.Infof("Publishing CAS volume to %s", targetPath)
    +
    +	if err := os.MkdirAll(targetPath, 0755); err != nil {
    +		klog.Errorf("Failed to create target path %s: %v", targetPath, err)
    +		return nil, fmt.Errorf("failed to create target path %s: %v", targetPath, err)
    +	}
    +
    +	// Check if already mounted
    +	notMnt, err := isNotMountPoint(targetPath)
    +	if err != nil {
    +		klog.Errorf("Failed to check if %s is a mount point: %v", targetPath, err)
    +		return nil, fmt.Errorf("failed to check if %s is a mount point: %v", targetPath, err)
    +	}
    +
    +	if notMnt {
    +		// Mount tmpfs filesystem to targetPath
    +		klog.Infof("Mounting tmpfs on %s", targetPath)
    +		if err := syscall.Mount("tmpfs", targetPath, "tmpfs", 0, ""); err != nil {
    +			klog.Errorf("Failed to mount tmpfs to %s: %v", targetPath, err)
    +			return nil, fmt.Errorf("failed to mount tmpfs to %s: %v", targetPath, err)
    +		}
    +	}
    +
    +	// Start CAS server under targetPath/.in-cluster-storage/api
    +	casDir := filepath.Join(targetPath, ".in-cluster-storage")
    +	if err := os.MkdirAll(casDir, 0777); err != nil {
    +		klog.Errorf("Failed to create CAS socket directory %s: %v", casDir, err)
    +		return nil, fmt.Errorf("failed to create CAS socket directory: %v", err)
    +	}
    +	if err := os.Chmod(casDir, 0777); err != nil {
    +		klog.Warningf("failed to chmod CAS socket directory %s: %v", casDir, err)
    +	}
    +
    +	casSocketPath := filepath.Join(casDir, "api")
    +	_ = os.Remove(casSocketPath)
    +
    +	klog.Infof("Starting CAS server on %s", casSocketPath)
    +	casSrv, err := cas.StartServer(casSocketPath, *storagePath, d.downloader)
    +	if err != nil {
    +		klog.Errorf("Failed to start CAS server at %s: %v", casSocketPath, err)
    +		return nil, fmt.Errorf("failed to start CAS server at %s: %v", casSocketPath, err)
    +	}
    +
    +	d.casServersMu.Lock()
    +	d.casServers[targetPath] = casSrv

    Let's just double-check that there is no existing casServer at targetPath

    justinsb justinsb commented on code on Jun 18, 2026 15:39 UTC
    Code Review
    cas/cmd/cas-node-daemon/main.go:1
    @@ -0,0 +1,306 @@
    +/*
    +Copyright 2026 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 main
    +
    +import (
    +	"context"
    +	"flag"
    +	"fmt"
    +	"io"
    +	"net"
    +	"os"
    +	"path/filepath"
    +	"strings"
    +	"sync"
    +	"syscall"
    +
    +	"github.com/container-storage-interface/spec/lib/go/csi"
    +	pb "github.com/gke-labs/in-cluster-storage/pkg/api/v1alpha1"
    +	"github.com/gke-labs/in-cluster-storage/cas/pkg/cas"
    +	"google.golang.org/grpc"
    +	"google.golang.org/grpc/credentials/insecure"
    +	"k8s.io/klog/v2"
    +)
    +
    +var (
    +	endpoint          = flag.String("endpoint", "unix:///tmp/csi.sock", "CSI endpoint")
    +	nodeID            = flag.String("nodeid", "", "node id")
    +	storagePath       = flag.String("storage-path", "/var/lib/cas", "Base path for storage")
    +	controllerAddress = flag.String("controller-address", "agentfs-controller:50051", "AgentFS Controller address")
    +)
    +
    +func main() {
    +	klog.InitFlags(nil)
    +	flag.Parse()
    +
    +	if *nodeID == "" {
    +		klog.Fatal("nodeid must be provided")
    +	}
    +
    +	if err := os.MkdirAll(*storagePath, 0755); err != nil {
    +		klog.Fatalf("failed to create storage path %s: %v", *storagePath, err)
    +	}
    +
    +	proto, addr, err := parseEndpoint(*endpoint)
    +	if err != nil {
    +		klog.Fatal(err)
    +	}
    +
    +	if proto == "unix" {
    +		addr = filepath.FromSlash(addr)
    +		if err := os.Remove(addr); err != nil && !os.IsNotExist(err) {
    +			klog.Fatalf("failed to remove %s: %v", addr, err)
    +		}
    +	}
    +
    +	listener, err := net.Listen(proto, addr)
    +	if err != nil {
    +		klog.Fatalf("failed to listen: %v", err)
    +	}
    +
    +	server := grpc.NewServer()
    +
    +	downloader := &controllerDownloader{
    +		controllerAddress: *controllerAddress,
    +	}
    +
    +	driver := &casCSIDriver{
    +		nodeID:     *nodeID,
    +		downloader: downloader,
    +		casServers: make(map[string]*cas.Server),
    +	}
    +
    +	csi.RegisterIdentityServer(server, driver)
    +	csi.RegisterNodeServer(server, driver)
    +
    +	klog.Infof("CAS CSI driver listening on %s", *endpoint)
    +	if err := server.Serve(listener); err != nil {
    +		klog.Fatalf("failed to serve: %v", err)
    +	}
    +}
    +
    +func parseEndpoint(endpoint string) (string, string, error) {
    +	parts := strings.SplitN(endpoint, "://", 2)
    +	if len(parts) != 2 {
    +		return "", "", fmt.Errorf("invalid endpoint: %s", endpoint)
    +	}
    +	scheme, addr := parts[0], parts[1]
    +	if scheme != "unix" && scheme != "tcp" {
    +		return "", "", fmt.Errorf("invalid endpoint: %s", endpoint)
    +	}
    +	return scheme, addr, nil
    +}
    +
    +type controllerDownloader struct {
    +	controllerAddress string
    +	conn              *grpc.ClientConn
    +	mu                sync.Mutex
    +}
    +
    +func (d *controllerDownloader) DownloadBlob(ctx context.Context, sha string, destPath string) error {
    +	d.mu.Lock()
    +	if d.conn == nil {
    +		conn, err := grpc.Dial(d.controllerAddress, grpc.WithTransportCredentials(insecure.NewCredentials()))
    +		if err != nil {
    +			d.mu.Unlock()
    +			return err
    +		}
    +		d.conn = conn
    +	}
    +	d.mu.Unlock()
    +
    +	client := pb.NewAgentFSControllerClient(d.conn)
    +	stream, err := client.DownloadBlob(ctx, &pb.DownloadBlobRequest{Sha256: sha})
    +	if err != nil {
    +		return err
    +	}
    +
    +	f, err := os.Create(destPath)
    +	if err != nil {
    +		return err
    +	}
    +	defer f.Close()
    +
    +	buffer := make([]byte, 1024*1024)
    +	for {
    +		resp, err := stream.Recv()
    +		if err == io.EOF {
    +			break
    +		}
    +		if err != nil {
    +			return err
    +		}
    +		// Write in chunks
    +		if _, err := f.Write(resp.Content); err != nil {
    +			return err
    +		}
    +		_ = buffer
    +	}
    +	return nil
    +}
    +
    +type casCSIDriver struct {
    +	csi.UnimplementedIdentityServer
    +	csi.UnimplementedNodeServer
    +
    +	nodeID     string
    +	downloader *controllerDownloader
    +
    +	casServersMu sync.Mutex
    +	casServers   map[string]*cas.Server
    +}
    +
    +func (d *casCSIDriver) GetPluginInfo(ctx context.Context, req *csi.GetPluginInfoRequest) (*csi.GetPluginInfoResponse, error) {
    +	return &csi.GetPluginInfoResponse{
    +		Name:          "cas.labs.gke.io",
    +		VendorVersion: "0.0.1",
    +	}, nil
    +}
    +
    +func (d *casCSIDriver) 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,
    +					},
    +				},
    +			},
    +		},
    +	}, nil
    +}
    +
    +func (d *casCSIDriver) Probe(ctx context.Context, req *csi.ProbeRequest) (*csi.ProbeResponse, error) {
    +	return &csi.ProbeResponse{}, nil
    +}
    +
    +func (d *casCSIDriver) NodeGetInfo(ctx context.Context, req *csi.NodeGetInfoRequest) (*csi.NodeGetInfoResponse, error) {
    +	return &csi.NodeGetInfoResponse{
    +		NodeId: d.nodeID,
    +	}, nil
    +}
    +
    +func (d *casCSIDriver) 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,
    +					},
    +				},
    +			},
    +		},
    +	}, nil
    +}
    +
    +func (d *casCSIDriver) NodePublishVolume(ctx context.Context, req *csi.NodePublishVolumeRequest) (*csi.NodePublishVolumeResponse, error) {
    +	targetPath := req.GetTargetPath()
    +	klog.Infof("Publishing CAS volume to %s", targetPath)
    +
    +	if err := os.MkdirAll(targetPath, 0755); err != nil {
    +		klog.Errorf("Failed to create target path %s: %v", targetPath, err)
    +		return nil, fmt.Errorf("failed to create target path %s: %v", targetPath, err)
    +	}
    +
    +	// Check if already mounted
    +	notMnt, err := isNotMountPoint(targetPath)
    +	if err != nil {
    +		klog.Errorf("Failed to check if %s is a mount point: %v", targetPath, err)
    +		return nil, fmt.Errorf("failed to check if %s is a mount point: %v", targetPath, err)
    +	}
    +
    +	if notMnt {
    +		// Mount tmpfs filesystem to targetPath
    +		klog.Infof("Mounting tmpfs on %s", targetPath)
    +		if err := syscall.Mount("tmpfs", targetPath, "tmpfs", 0, ""); err != nil {
    +			klog.Errorf("Failed to mount tmpfs to %s: %v", targetPath, err)
    +			return nil, fmt.Errorf("failed to mount tmpfs to %s: %v", targetPath, err)
    +		}
    +	}
    +
    +	// Start CAS server under targetPath/.in-cluster-storage/api
    +	casDir := filepath.Join(targetPath, ".in-cluster-storage")
    +	if err := os.MkdirAll(casDir, 0777); err != nil {
    +		klog.Errorf("Failed to create CAS socket directory %s: %v", casDir, err)
    +		return nil, fmt.Errorf("failed to create CAS socket directory: %v", err)
    +	}
    +	if err := os.Chmod(casDir, 0777); err != nil {
    +		klog.Warningf("failed to chmod CAS socket directory %s: %v", casDir, err)
    +	}
    +
    +	casSocketPath := filepath.Join(casDir, "api")
    +	_ = os.Remove(casSocketPath)
    +
    +	klog.Infof("Starting CAS server on %s", casSocketPath)
    +	casSrv, err := cas.StartServer(casSocketPath, *storagePath, d.downloader)
    +	if err != nil {
    +		klog.Errorf("Failed to start CAS server at %s: %v", casSocketPath, err)
    +		return nil, fmt.Errorf("failed to start CAS server at %s: %v", casSocketPath, err)
    +	}
    +
    +	d.casServersMu.Lock()
    +	d.casServers[targetPath] = casSrv
    +	d.casServersMu.Unlock()
    +
    +	klog.Infof("Successfully published CAS volume to %s", targetPath)
    +	return &csi.NodePublishVolumeResponse{}, nil
    +}
    +
    +func (d *casCSIDriver) NodeUnpublishVolume(ctx context.Context, req *csi.NodeUnpublishVolumeRequest) (*csi.NodeUnpublishVolumeResponse, error) {
    +	targetPath := req.GetTargetPath()
    +	klog.Infof("Unpublishing CAS volume from %s", targetPath)
    +
    +	// Stop and remove the CAS server
    +	d.casServersMu.Lock()
    +	if srv, exists := d.casServers[targetPath]; exists {

    Let's warn if it does not exist, that's unexpected

    justinsb justinsb commented on code on Jun 18, 2026 15:40 UTC
    Code Review
    cas/pkg/cas/client.go:1
    @@ -0,0 +1,105 @@
    +/*
    +Copyright 2026 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 cas
    +
    +import (
    +	"fmt"
    +	"net"
    +	"os"
    +	"strconv"
    +	"strings"
    +	"syscall"
    +
    +	"golang.org/x/sys/unix"
    +)
    +
    +// Client represents a client for the CAS UDS server.
    +type Client struct {
    +	socketPath string
    +}
    +
    +// NewClient creates a new Client pointing to the given UDS socketPath.
    +func NewClient(socketPath string) *Client {
    +	return &Client{socketPath: socketPath}
    +}
    +
    +// RequestBlob requests the blob with the given SHA256 from the CAS server,
    +// and returns the open *os.File pointing to that blob (using SCM_RIGHTS) along with the file size.
    +func (c *Client) RequestBlob(sha string) (*os.File, int64, error) {
    +	conn, err := net.Dial("unix", c.socketPath)
    +	if err != nil {
    +		return nil, 0, fmt.Errorf("failed to connect to CAS socket %s: %v", c.socketPath, err)
    +	}
    +	defer conn.Close()

    Let's open the connection in NewClient, and reuse it until we Close() the Client

    justinsb justinsb commented on code on Jun 18, 2026 15:40 UTC
    Code Review
    cas/pkg/cas/client.go:1
    @@ -0,0 +1,105 @@
    +/*
    +Copyright 2026 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 cas
    +
    +import (
    +	"fmt"
    +	"net"
    +	"os"
    +	"strconv"
    +	"strings"
    +	"syscall"
    +
    +	"golang.org/x/sys/unix"
    +)
    +
    +// Client represents a client for the CAS UDS server.
    +type Client struct {
    +	socketPath string
    +}
    +
    +// NewClient creates a new Client pointing to the given UDS socketPath.
    +func NewClient(socketPath string) *Client {
    +	return &Client{socketPath: socketPath}
    +}
    +
    +// RequestBlob requests the blob with the given SHA256 from the CAS server,
    +// and returns the open *os.File pointing to that blob (using SCM_RIGHTS) along with the file size.
    +func (c *Client) RequestBlob(sha string) (*os.File, int64, error) {
    +	conn, err := net.Dial("unix", c.socketPath)
    +	if err != nil {
    +		return nil, 0, fmt.Errorf("failed to connect to CAS socket %s: %v", c.socketPath, err)
    +	}
    +	defer conn.Close()
    +
    +	unixConn, ok := conn.(*net.UnixConn)
    +	if !ok {
    +		return nil, 0, fmt.Errorf("connection is not a unix connection")
    +	}
    +
    +	req := fmt.Sprintf("GET %s\n", sha)

    Can we not use GRPC?

    justinsb justinsb commented on code on Jun 18, 2026 15:41 UTC
    Code Review
    cas/pkg/cas/server.go:1
    @@ -0,0 +1,254 @@
    +/*
    +Copyright 2026 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 cas
    +
    +import (
    +	"bufio"
    +	"context"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net"
    +	"os"
    +	"path/filepath"
    +	"strings"
    +	"sync"
    +
    +	"golang.org/x/sys/unix"
    +	"k8s.io/klog/v2"
    +)
    +
    +// BlobDownloader interface abstracts the downloading of a blob from a remote/controller.
    +type BlobDownloader interface {
    +	DownloadBlob(ctx context.Context, sha string, destPath string) error
    +}
    +
    +// Server implements the Unix Domain Socket CAS API.
    +type Server struct {
    +	socketPath string
    +	storageDir string
    +	downloader BlobDownloader
    +
    +	listener net.Listener
    +	stopCh   chan struct{}
    +	wg       sync.WaitGroup
    +
    +	connsMu sync.Mutex
    +	conns   map[net.Conn]struct{}
    +}
    +
    +var chdirMu sync.Mutex
    +
    +// StartServer starts listening on the specified socketPath.
    +func StartServer(socketPath, storageDir string, downloader BlobDownloader) (*Server, error) {
    +	// Ensure the parent directory of socket exists
    +	parentDir := filepath.Dir(socketPath)
    +	if err := os.MkdirAll(parentDir, 0777); err != nil {
    +		return nil, fmt.Errorf("failed to create directory for socket: %v", err)
    +	}
    +
    +	chdirMu.Lock()
    +	defer chdirMu.Unlock()
    +
    +	oldWD, err := os.Getwd()
    +	if err != nil {
    +		return nil, fmt.Errorf("failed to get current working directory: %v", err)
    +	}
    +
    +	if err := os.Chdir(parentDir); err != nil {

    Let's add a comment about why we're calling chdir, it's unobvious (IMO)

    justinsb justinsb commented on code on Jun 18, 2026 15:42 UTC
    Code Review
    cas/pkg/cas/server.go:1
    @@ -0,0 +1,254 @@
    +/*
    +Copyright 2026 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 cas
    +
    +import (
    +	"bufio"
    +	"context"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net"
    +	"os"
    +	"path/filepath"
    +	"strings"
    +	"sync"
    +
    +	"golang.org/x/sys/unix"
    +	"k8s.io/klog/v2"
    +)
    +
    +// BlobDownloader interface abstracts the downloading of a blob from a remote/controller.
    +type BlobDownloader interface {
    +	DownloadBlob(ctx context.Context, sha string, destPath string) error
    +}
    +
    +// Server implements the Unix Domain Socket CAS API.
    +type Server struct {
    +	socketPath string
    +	storageDir string
    +	downloader BlobDownloader
    +
    +	listener net.Listener
    +	stopCh   chan struct{}
    +	wg       sync.WaitGroup
    +
    +	connsMu sync.Mutex
    +	conns   map[net.Conn]struct{}
    +}
    +
    +var chdirMu sync.Mutex
    +
    +// StartServer starts listening on the specified socketPath.
    +func StartServer(socketPath, storageDir string, downloader BlobDownloader) (*Server, error) {
    +	// Ensure the parent directory of socket exists
    +	parentDir := filepath.Dir(socketPath)
    +	if err := os.MkdirAll(parentDir, 0777); err != nil {
    +		return nil, fmt.Errorf("failed to create directory for socket: %v", err)
    +	}
    +
    +	chdirMu.Lock()
    +	defer chdirMu.Unlock()
    +
    +	oldWD, err := os.Getwd()
    +	if err != nil {
    +		return nil, fmt.Errorf("failed to get current working directory: %v", err)
    +	}
    +
    +	if err := os.Chdir(parentDir); err != nil {
    +		return nil, fmt.Errorf("failed to change directory to %s: %v", parentDir, err)
    +	}
    +
    +	// Listen on relative socket name to bypass the 108-character limit
    +	socketName := filepath.Base(socketPath)
    +	listener, err := net.Listen("unix", socketName)
    +
    +	// Restore working directory immediately
    +	if chdirErr := os.Chdir(oldWD); chdirErr != nil {
    +		klog.Warningf("failed to restore working directory to %s: %v", oldWD, chdirErr)
    +	}
    +
    +	if err != nil {
    +		return nil, fmt.Errorf("failed to listen on unix socket %s (relative %s): %v", socketPath, socketName, err)
    +	}
    +
    +	// Make the socket writeable for any user in the container
    +	if err := os.Chmod(socketPath, 0777); err != nil {
    +		klog.Warningf("failed to chmod socket %s: %v", socketPath, err)
    +	}
    +
    +	srv := &Server{
    +		socketPath: socketPath,
    +		storageDir: storageDir,
    +		downloader: downloader,
    +		listener:   listener,
    +		stopCh:     make(chan struct{}),
    +		conns:      make(map[net.Conn]struct{}),
    +	}
    +
    +	srv.wg.Add(1)
    +	go srv.serve()
    +
    +	return srv, nil
    +}
    +
    +func (s *Server) serve() {
    +	defer s.wg.Done()
    +	for {
    +		conn, err := s.listener.Accept()
    +		if err != nil {
    +			select {
    +			case <-s.stopCh:
    +				return
    +			default:
    +				klog.Errorf("CAS server accept error: %v", err)
    +				return
    +			}
    +		}
    +
    +		s.connsMu.Lock()
    +		s.conns[conn] = struct{}{}
    +		s.connsMu.Unlock()
    +
    +		go s.handleConnection(conn)
    +	}
    +}
    +
    +func (s *Server) handleConnection(conn net.Conn) {
    +	defer func() {
    +		conn.Close()
    +		s.connsMu.Lock()
    +		delete(s.conns, conn)
    +		s.connsMu.Unlock()
    +	}()
    +
    +	unixConn, ok := conn.(*net.UnixConn)
    +	if !ok {
    +		klog.Errorf("CAS server: accepted connection is not a unix connection")
    +		return
    +	}
    +
    +	reader := bufio.NewReader(unixConn)
    +	for {
    +		line, err := reader.ReadString('\n')
    +		if err != nil {
    +			if !errors.Is(err, io.EOF) {
    +				klog.Errorf("CAS server: read error: %v", err)
    +			}
    +			return
    +		}
    +
    +		line = strings.TrimSpace(line)
    +		if line == "" {
    +			continue
    +		}
    +
    +		parts := strings.SplitN(line, " ", 2)
    +		if len(parts) != 2 || strings.ToUpper(parts[0]) != "GET" {
    +			s.sendError(unixConn, "invalid command: expected GET <sha256>")
    +			continue
    +		}
    +
    +		sha := strings.ToLower(strings.TrimSpace(parts[1]))
    +		if !isValidSHA256(sha) {
    +			s.sendError(unixConn, "invalid sha256 format")
    +			continue
    +		}
    +
    +		s.handleGet(unixConn, sha)
    +	}
    +}
    +
    +func (s *Server) handleGet(conn *net.UnixConn, sha string) {
    +	blobsDir := filepath.Join(s.storageDir, "blobs")
    +	if err := os.MkdirAll(blobsDir, 0755); err != nil {
    +		s.sendError(conn, fmt.Sprintf("failed to create blobs directory: %v", err))
    +		return
    +	}
    +
    +	blobPath := filepath.Join(blobsDir, sha)
    +
    +	// Check if the file exists
    +	if _, err := os.Stat(blobPath); os.IsNotExist(err) {

    It's probably easier to try to Open it here and download if we get os.IsNotExist

    justinsb justinsb commented on code on Jun 18, 2026 15:43 UTC
    Code Review
    cas/pkg/cas/server.go:1
    @@ -0,0 +1,254 @@
    +/*
    +Copyright 2026 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 cas
    +
    +import (
    +	"bufio"
    +	"context"
    +	"errors"
    +	"fmt"
    +	"io"
    +	"net"
    +	"os"
    +	"path/filepath"
    +	"strings"
    +	"sync"
    +
    +	"golang.org/x/sys/unix"
    +	"k8s.io/klog/v2"
    +)
    +
    +// BlobDownloader interface abstracts the downloading of a blob from a remote/controller.
    +type BlobDownloader interface {
    +	DownloadBlob(ctx context.Context, sha string, destPath string) error
    +}
    +
    +// Server implements the Unix Domain Socket CAS API.
    +type Server struct {
    +	socketPath string
    +	storageDir string
    +	downloader BlobDownloader
    +
    +	listener net.Listener
    +	stopCh   chan struct{}
    +	wg       sync.WaitGroup
    +
    +	connsMu sync.Mutex
    +	conns   map[net.Conn]struct{}
    +}
    +
    +var chdirMu sync.Mutex
    +
    +// StartServer starts listening on the specified socketPath.
    +func StartServer(socketPath, storageDir string, downloader BlobDownloader) (*Server, error) {
    +	// Ensure the parent directory of socket exists
    +	parentDir := filepath.Dir(socketPath)
    +	if err := os.MkdirAll(parentDir, 0777); err != nil {
    +		return nil, fmt.Errorf("failed to create directory for socket: %v", err)
    +	}
    +
    +	chdirMu.Lock()
    +	defer chdirMu.Unlock()
    +
    +	oldWD, err := os.Getwd()
    +	if err != nil {
    +		return nil, fmt.Errorf("failed to get current working directory: %v", err)
    +	}
    +
    +	if err := os.Chdir(parentDir); err != nil {
    +		return nil, fmt.Errorf("failed to change directory to %s: %v", parentDir, err)
    +	}
    +
    +	// Listen on relative socket name to bypass the 108-character limit
    +	socketName := filepath.Base(socketPath)
    +	listener, err := net.Listen("unix", socketName)
    +
    +	// Restore working directory immediately
    +	if chdirErr := os.Chdir(oldWD); chdirErr != nil {
    +		klog.Warningf("failed to restore working directory to %s: %v", oldWD, chdirErr)
    +	}
    +
    +	if err != nil {
    +		return nil, fmt.Errorf("failed to listen on unix socket %s (relative %s): %v", socketPath, socketName, err)
    +	}
    +
    +	// Make the socket writeable for any user in the container
    +	if err := os.Chmod(socketPath, 0777); err != nil {
    +		klog.Warningf("failed to chmod socket %s: %v", socketPath, err)
    +	}
    +
    +	srv := &Server{
    +		socketPath: socketPath,
    +		storageDir: storageDir,
    +		downloader: downloader,
    +		listener:   listener,
    +		stopCh:     make(chan struct{}),
    +		conns:      make(map[net.Conn]struct{}),
    +	}
    +
    +	srv.wg.Add(1)
    +	go srv.serve()
    +
    +	return srv, nil
    +}
    +
    +func (s *Server) serve() {
    +	defer s.wg.Done()
    +	for {
    +		conn, err := s.listener.Accept()
    +		if err != nil {
    +			select {
    +			case <-s.stopCh:
    +				return
    +			default:
    +				klog.Errorf("CAS server accept error: %v", err)
    +				return
    +			}
    +		}
    +
    +		s.connsMu.Lock()
    +		s.conns[conn] = struct{}{}
    +		s.connsMu.Unlock()
    +
    +		go s.handleConnection(conn)
    +	}
    +}
    +
    +func (s *Server) handleConnection(conn net.Conn) {
    +	defer func() {
    +		conn.Close()
    +		s.connsMu.Lock()
    +		delete(s.conns, conn)
    +		s.connsMu.Unlock()
    +	}()
    +
    +	unixConn, ok := conn.(*net.UnixConn)
    +	if !ok {
    +		klog.Errorf("CAS server: accepted connection is not a unix connection")
    +		return
    +	}
    +
    +	reader := bufio.NewReader(unixConn)
    +	for {
    +		line, err := reader.ReadString('\n')
    +		if err != nil {
    +			if !errors.Is(err, io.EOF) {
    +				klog.Errorf("CAS server: read error: %v", err)
    +			}
    +			return
    +		}
    +
    +		line = strings.TrimSpace(line)
    +		if line == "" {
    +			continue
    +		}
    +
    +		parts := strings.SplitN(line, " ", 2)
    +		if len(parts) != 2 || strings.ToUpper(parts[0]) != "GET" {
    +			s.sendError(unixConn, "invalid command: expected GET <sha256>")
    +			continue
    +		}
    +
    +		sha := strings.ToLower(strings.TrimSpace(parts[1]))
    +		if !isValidSHA256(sha) {
    +			s.sendError(unixConn, "invalid sha256 format")
    +			continue
    +		}
    +
    +		s.handleGet(unixConn, sha)
    +	}
    +}
    +
    +func (s *Server) handleGet(conn *net.UnixConn, sha string) {
    +	blobsDir := filepath.Join(s.storageDir, "blobs")
    +	if err := os.MkdirAll(blobsDir, 0755); err != nil {
    +		s.sendError(conn, fmt.Sprintf("failed to create blobs directory: %v", err))
    +		return
    +	}
    +
    +	blobPath := filepath.Join(blobsDir, sha)
    +
    +	// Check if the file exists
    +	if _, err := os.Stat(blobPath); os.IsNotExist(err) {
    +		klog.Infof("CAS server: blob %s not found locally, downloading...", sha)
    +		ctx := context.Background()
    +		if err := s.downloader.DownloadBlob(ctx, sha, blobPath); err != nil {
    +			klog.Errorf("CAS server: failed to download blob %s: %v", sha, err)
    +			s.sendError(conn, fmt.Sprintf("failed to download blob: %v", err))
    +			return
    +		}
    +	}
    +
    +	// Open the file
    +	file, err := os.Open(blobPath)
    +	if err != nil {
    +		klog.Errorf("CAS server: failed to open blob %s: %v", sha, err)
    +		s.sendError(conn, fmt.Sprintf("failed to open blob: %v", err))
    +		return
    +	}
    +	defer file.Close()
    +
    +	fi, err := file.Stat()
    +	if err != nil {
    +		klog.Errorf("CAS server: failed to stat blob %s: %v", sha, err)
    +		s.sendError(conn, fmt.Sprintf("failed to stat blob: %v", err))
    +		return
    +	}
    +
    +	// Send file descriptor using SCM_RIGHTS
    +	rights := unix.UnixRights(int(file.Fd()))
    +	resp := fmt.Sprintf("OK %d\n", fi.Size())
    +	_, _, err = conn.WriteMsgUnix([]byte(resp), rights, nil)
    +	if err != nil {
    +		klog.Errorf("CAS server: failed to send file descriptor: %v", err)
    +		return
    +	}
    +}
    +
    +func (s *Server) sendError(conn *net.UnixConn, errMsg string) {
    +	resp := fmt.Sprintf("ERR %s\n", errMsg)
    +	_, _ = conn.Write([]byte(resp))
    +}
    +
    +// Stop closes the listener, aborts active connections, and cleans up the socket file.
    +func (s *Server) Stop() {
    +	close(s.stopCh)
    +	s.listener.Close()
    +
    +	s.connsMu.Lock()
    +	for conn := range s.conns {
    +		conn.Close()
    +	}
    +	s.connsMu.Unlock()
    +
    +	s.wg.Wait()
    +	_ = os.Remove(s.socketPath)
    +}
    +
    +// isValidSHA256 returns true if s is a 64-char hex SHA-256 hash.
    +func isValidSHA256(s string) bool {

    Maybe we should normalize (convert to lower case) and return this as a type BlobID string just to represent that this is a validated and normalized blob id

    justinsb justinsb commented on code on Jun 18, 2026 15:44 UTC
    Code Review
    tests/e2e/e2e_test.go:1
    @@ -79,6 +84,104 @@ func TestE2E(t *testing.T) {
     		t.Fatalf("AgentFS Node Daemon failed to start: %v", err)
     	}
     
    +	// Deploy and wait for CAS CSI driver

    Can we create a separate e2e test in tests/e2e? I'm OK with the code duplication around launching a cluster, we can tackle that later!

    Reviewers
    Assignees
    codebot-robot codebot-robot
    Labels
    risk: low confidence: 88.8% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 60.6% (MEDIUM) · Higher = larger blast radius
    60.6%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 88.8% · Lower = rushed or shallow review
    88.8%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 6.8% · Safe to merge
    6.8%