Cloud Native 13 min read

How to Build a Go-Based Kubernetes PVC Watcher with client-go

This tutorial shows how to use the Go client-go library to create a command‑line tool that lists PersistentVolumeClaims, watches PVC events in a Kubernetes cluster, and triggers actions when total claimed storage exceeds a configurable threshold.

MaGe Linux Operations
MaGe Linux Operations
MaGe Linux Operations
How to Build a Go-Based Kubernetes PVC Watcher with client-go

Kubernetes is written in Go, and its native Go client (client-go) provides convenient API access. This article demonstrates how to use client-go to build a simple command‑line tool that watches PersistentVolumeClaims (PVCs) in a Kubernetes cluster.

Kubernetes Go Client (client-go)

client-go is the oldest Kubernetes client library. It does not use Swagger generators; instead it uses code generators from the Kubernetes project to produce Go‑style objects and serializers. The library consists of a set of packages that satisfy programming needs from simple REST primitives to complex clients.

RESTClient is a foundational package that uses the api‑machinery types to provide REST primitives. On top of RESTClient, the clientset is the entry point for creating Kubernetes client tools, exposing typed APIs and their serializers.

Note: client-go also includes packages such as discovery, dynamic, and scale, which are not covered here but are useful to know.

A Simple Kubernetes Client Tool

The example tool, pvcwatch , is a command‑line program that monitors the total PVC capacity in a namespace and triggers an action (printing a notification) when a threshold is reached.

Setup

client-go supports vendor management with Godep or dep; this guide uses dep. The minimal Gopkg.toml for client-go v6.0 and Kubernetes API v1.9 is:

[[constraint]]
  name = "k8s.io/api"
  version = "kubernetes-1.9.0"
[[constraint]]
  name = "k8s.io/apimachinery"
  version = "kubernetes-1.9.0"
[[constraint]]
  name = "k8s.io/client-go"
  version = "6.0.0"

Run dep ensure to fetch the dependencies.

Connecting to the API Server

The first step is to build a configuration from a kubeconfig file using clientcmd:

import (
    "k8s.io/client-go/tools/clientcmd"
    // other imports
)

func main() {
    kubeconfig := filepath.Join(os.Getenv("HOME"), ".kube", "config")
    config, err := clientcmd.BuildConfigFromFlags("", kubeconfig)
    if err != nil {
        log.Fatal(err)
    }
    // ...
}

You can also obtain a configuration from within a cluster using clientcmd.BuildConfigFromFlags("", "") or rest.InClusterConfig().

Creating a clientset

With a valid config, initialize a clientset:

clientset, err := kubernetes.NewForConfig(config)
if err != nil {
    log.Fatal(err)
}
api := clientset.CoreV1()

Listing PVCs in a Namespace

Use

clientset.CoreV1().PersistentVolumeClaims(namespace).List(listOptions)

to retrieve PVCs. ListOptions can filter by label, field, and namespace.

listOptions := metav1.ListOptions{
    LabelSelector: label,
    FieldSelector: field,
}
pvcs, err := api.PersistentVolumeClaims(ns).List(listOptions)
if err != nil {
    log.Fatal(err)
}
printPVCs(pvcs)

The helper printPVCs formats the output:

func printPVCs(pvcs *v1.PersistentVolumeClaimList) {
    template := "%‑32s%-8s%-8s
"
    fmt.Printf(template, "NAME", "STATUS", "CAPACITY")
    for _, pvc := range pvcs.Items {
        quant := pvc.Spec.Resources.Requests[v1.ResourceStorage]
        fmt.Printf(template, pvc.Name, string(pvc.Status.Phase), quant.String())
    }
}

Watching PVC Events

client-go can watch for Added, Modified, and Deleted events on PVCs. The watcher returns a channel via ResultChan():

watcher, err := api.PersistentVolumeClaims(ns).Watch(listOptions)
if err != nil {
    log.Fatal(err)
}
ch := watcher.ResultChan()

Two resource.Quantity variables track the maximum allowed claims ( maxClaimsQuant) and the current total ( totalClaimQuant).

var maxClaims string
flag.StringVar(&maxClaims, "max-claims", "200Gi", "Maximum total claims to watch")
var totalClaimedQuant resource.Quantity
maxClaimedQuant := resource.MustParse(maxClaims)

In the event loop, handle watch.Added by adding the PVC’s requested storage to totalClaimedQuant and checking against the threshold; handle watch.Deleted by subtracting the storage.

for event := range ch {
    pvc, ok := event.Object.(*v1.PersistentVolumeClaim)
    if !ok {
        log.Fatal("unexpected type")
    }
    quant := pvc.Spec.Resources.Requests[v1.ResourceStorage]
    switch event.Type {
    case watch.Added:
        totalClaimedQuant.Add(quant)
        log.Printf("PVC %s added, claim size %s", pvc.Name, quant.String())
        if totalClaimedQuant.Cmp(maxClaimedQuant) == 1 {
            log.Printf("Claim overage reached: max %s at %s", maxClaimedQuant.String(), totalClaimedQuant.String())
            log.Println("*** Taking action ***")
        }
    case watch.Deleted:
        totalClaimedQuant.Sub(quant)
        log.Printf("PVC %s removed, size %s", pvc.Name, quant.String())
        if totalClaimedQuant.Cmp(maxClaimedQuant) <= 0 {
            log.Printf("Claim usage normal: max %s at %s", maxClaimedQuant.String(), totalClaimedQuant.String())
            log.Println("*** Taking action ***")
        }
    }
}

Running the Program

When executed inside a running cluster, the tool first lists existing PVCs, then starts watching for new PVC events. Adding a PVC that pushes the total usage above the configured limit triggers the defined action (printing a warning).

Example output shows PVC listings, percentage usage, and alerts when the threshold (e.g., 200 Gi) is exceeded.

Summary

This article is part of a series on using the official Go client for Kubernetes to interact with the API server. It walks through building a command‑line utility that monitors PVC capacity in a namespace, lists existing PVCs, and watches for resource events to trigger actions based on usage thresholds.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

cloud-nativeKubernetesGoWatcherclient-goPVC
MaGe Linux Operations
Written by

MaGe Linux Operations

Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.